Install direct installation instead of npm for Node module?

I want to force yarn install instead of npm install . I want to increase the error in npm install . What to do in package.json ?

+8
npm yarnpkg
source share
4 answers

In your pre-installation script, you can run a mini-node script that should work on all platforms, while things like pgrep (and other common commands and * nix operators) won't work on Windows until Windows 10 has become widespread.

I checked below script on node v4.7.0 (npm v2.15.11) and node v7.2.1 (npm v3.10.10). I assume that this works in everything that happens between them. It works by checking environment variables in the currently running process. npm_execpath is the path to the current run of the "npm" script. In the case of yarn, it should point to /path/to/yarn/on/your/machine/yarn.js .

 "scripts": { "preinstall": "node -e \"if(process.env.npm_execpath.indexOf('yarn') === -1) throw new Error('You must use Yarn to install, not NPM')\"" } 

NOTE: Update from Alexander's answer - this will not work if the user uses npm install --ignore-scripts . Please give a loan when a loan should be.

Here you can learn more about npm scripts: https://docs.npmjs.com/misc/scripts

As for the npm_execpath environment npm_execpath , but not documented, I doubt it will ever change. This has been around several major releases of npm , and in fact this does not mean that it is the best name for this test.

+11
source share

Like the other answers, I would recommend using a preinstall script and checking your environment. For a portable solution that won't have false positives if another npm process happens, using node -e 'JS_CODE' is probably the best option.

In this JS code, you can check the package manager path using the following:

 process.env.npm_execpath 

Binary yarn yarn.js , compared to npm-cli.js used by NPM. We can use a regular expression like the following to check if this line ends with yarn.js

 /yarn\.js$/ 

Using this regular expression, we can be sure that it will not accidentally match somewhere earlier in the file system. Most likely, yarn will not appear in the file path, but you can never be sure.

Here's a minimal example:

 { "name": "test", "version": "1.0.0", "scripts": { "preinstall": "node -e 'if(!/yarn\\.js$/.test(process.env.npm_execpath))throw new Error(\"Use yarn\")'" } } 

Of course, the user can still get around this check by editing JSON or using the --ignore-scripts options:

 npm install --ignore-scripts 
+2
source share

For this you can use preinstall with some shell script.

sample package.json:

  "scripts": { "preinstall": "pgrep npm && exit 1" } 
+1
source share

I just released a module that includes a CLI for this (useful for npm preinstall ): https://github.com/adjohnson916/use-yarn

Also, I just released the Danger helper to check for any changes to yarn.lock in CI: https://github.com/adjohnson916/danger-yarn-lock

See also discussion here:

+1
source share