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
Alexander O'Mara
source share