Brett DeWoody
Brett DeWoody

Reputation: 62743

Prevent Yarn install from running in project (i.e. force NPM install)

We recently switched back to using NPM from Yarn, but old habits die hard and I'm worried some devs will accidentally use yarn install.

How can I prevent yarn install from being run in the project? Or, even better, display a reminder to use npm install?

I'm thinking the yarn install can be intercepted with a preinstall script, but I'm not sure what to look for in the preinstall script.

Upvotes: 11

Views: 3380

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 121945

I thought of another option, using the fact that Yarn will check its version against $.engines.yarn in package.json. If you set this as follows:

{
  ...
  "engines": {
    "yarn": "use npm!"
  }
}

Yarn will bail out, albeit with a slightly cryptic error message:

yarn install v{foo}
info No lockfile found.
[1/5] 🔍  Validating package.json...
error {bar}@{baz}: The engine "yarn" is incompatible with this module. Expected version "use npm!". Got "{foo}"
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Upvotes: 17

jonrsharpe
jonrsharpe

Reputation: 121945

You can see whether it's Yarn or NPM running by looking at the value of the npm_execpath environment variable. If you did something like:

"preinstall": "if [[ $npm_execpath =~ 'yarn' ]]; then echo 'Use NPM!' && exit 1; fi",

Then yarn install (or just yarn) would fail prior to the install step. If you want to make this cross-platform or you're not using *nix, then you could write a simple script like:

#! /usr/bin/env node

if (process.env.npm_execpath.match(/yarn/)) {
  console.log("Use NPM!");
  process.exit(1);
}

and run that in preinstall.

Upvotes: 12

Related Questions