Using Yarn With Angular

One of the most infuriating parts of a new project setup is the npm install. A new Angular project from the CLI (Running “ng new”) can even take several minutes. And even if it’s an existing project that you know you have already setup, but you just want to check, a simple npm install can still take 30 seconds just to say “Yep all good here!”.

An option you see get thrown around often is to switch to using Yarn. Using Yarn from the command line is very similar to NPM (Infact we have a NPM vs Yarn Cheatsheet right here!), but what you’ll quickly find is that Yarn is so much more performant. The biggest reason is that Yarn has an offline global cache on your computer so repeated installs of the same package (For example, creating new Angular projects over and over again), will simply utilize the cached version rather than downloading the package all over again over the internet. Sounds good to me!

Adding Yarn after the fact to an existing project may be relatively straight forward. But what we are actually looking for is the ability to use Yarn with the actual internal angular cli when it tries to install a package.

Using Yarn Globally

If you want to use Yarn globally for *all* Angular projects on your machine, then all you need to do is run :

ng config -g cli.packageManager yarn

This updates the .angular-config.json inside C:\Users\YourUser on Windows to look like so :

{
  "version": 1,
  "cli": {
    "analytics": false,
    "packageManager": "yarn"
  }
}

Using Yarn On A Single Project

Sometimes you don’t want to globally use Yarn, and you just want to set it up on a new project you are about to create. This can be a bit of a headache as the initial call to ng new is the the most painful part of the entire process as it will use npm to install all the base packages, even if once the project is setup you switch to Yarn.

But we have a bit of a cheatcode to get around it!

When creating our project we can run :

ng new --skip-install

Where the skip install flag will actually skip over the final npm install after creating the project. From there, we can run the following command *from inside the project* :

ng config cli.packageManager yarn

Notice how we don’t have the -g flag like before. This sets up yarn as the package manager for this project only. From there, we just run

yarn

And the initial install of Angular components will happen like they normally would on an ng new command, but using Yarn instead.

Leave a Reply

Your email address will not be published. Required fields are marked *