How To Force Use Yarn Or NPM

force-yarn-install-or-npm

In this short post, I’m going to show you how to prevent the usage of npm or yarn, depending on your needs.
Let’s get started!

Edit .npmrc

You might not have this file in your codebase. If this is the case, create this file in the root folder of your application.
It allows us to specify package managers configurations and it is used by both npm and yarn.
Your .npmrc file should have the engine-strict property marked as true.


//.npmrc
engine-strict = true

This option tells the package manager to use the version of the engines we have specified in the package.json file.

Edit package.json

Inside your package.json file you should add the engines section if you don’t currently have it.


//package.json
{ 
  ...
  "engines": {
    "npm": "please-use-yarn",
    "yarn": ">= 1.19.1"
  },
  ...
}

In the above code, the package.json file uses a version of yarn 1.19.1 or greater.
But for npm we specify a version that doesn’t exist.

This way we make sure that when someone tries to use npm instead of yarn, he or she will receive an error that outputs ‘please-use-yarn‘.

Running npm install

Once you’ve done the above changes, try to run npm install.

You will receive an error that prevents you from using npm.


npm ERR! code ENOTSUP
npm ERR! notsup Unsupported engine for [email protected]: wanted: {"npm":"please-use-yarn","yarn":">= 1.19.1"} (current:
 {"node":"12.16.3","npm":"6.14.4"})
npm ERR! notsup Not compatible with your version of node/npm: [email protected]
npm ERR! notsup Not compatible with your version of node/npm: [email protected]
npm ERR! notsup Required: {"npm":"please-use-yarn","yarn":">= 1.19.1"}
npm ERR! notsup Actual:   {"npm":"6.14.4","node":"12.16.3"}

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\YourUser\AppData\Roaming\npm-cache\_logs\2020-05-21T10_21_04_676Z-debug.log

This, of course, can be done the other way around if you want to prevent the usage of yarn.

Conclusion

It is pretty straightforward and easy to ensure that only one package manager must be used inside your project.
This will reduce the chance of errors caused by developers that are using different package managers and it is a good practice to standardize the project’s coding rules and management.

I hope you find this tip useful and let me know what you think about the post through comments below, or on Twitter at @pelu_carol

If you find this article helpful, please share it with others and subscribe to the blog to support me and receive a bi-monthly-ish e-mail notification on my latest articles.

Carol Pelu
Follow me

You may also like...