阻止项目中 运行 的 Yarn 安装(即强制 NPM 安装)

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

我们最近从 Yarn 切换回使用 NPM,但旧习惯很难改掉,我担心一些开发人员会不小心使用 yarn install

如何防止 yarn install 在项目中成为 运行?或者,更好的是,显示使用 npm install 的提醒?

我认为 yarn install 可以用 preinstall 脚本拦截,但我不确定要在 preinstall 脚本中查找什么。

你可以通过查看npm_execpath环境变量的值来判断是Yarn还是NPM 运行ning。如果你做了类似的事情:

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

然后 yarn install(或只是 yarn)将在安装步骤之前失败。如果你想让这个跨平台或者你不使用 *nix,那么你可以编写一个简单的脚本,如:

#! /usr/bin/env node

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

和 运行 preinstall.

我想到了另一种选择,利用 Yarn 将在 package.json 中根据 $.engines.yarn 检查其版本这一事实。如果你这样设置:

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

Yarn 将退出,尽管会出现一条稍微神秘的错误消息:

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.