scripts-prepend-node-path

Node.js

在使用服务器编译上线包的过程中,可能会使用 nvm 来管理编译使用的 Node.js 版本。此时,运行时 Node.js 的二进制文件和实际服务器本身的 Node.js 文件将会是不同的。

这样做的好处是可以隔离,保证编译的环境是稳定的。

但是,当 npm 试图运行 Node.js 的时候,就要格外小心了。默认情况下,npm 会使用 path 中定义的 Node.js 版本。而对于打包服务器来说,这个 path 上的 Node.js 很可能并不是 nvm 管理的那个版本。

举个例子,如果 package.json 中定义了 postinstall 的脚本,如下;

{
  "scripts": {
    "postinstall": "some-cli"
  }
}

那么,在 yarn install 之后,执行这个 postinstall 的过程中,some-cli 需要 Node.js 来执行,而 npm 使用的 Node.js 是 path 上的默认版本,和 nvm 管理的并不是同一个。命令行会有如下的报错:

npm WARN lifecycle The node binary used for scripts is xxx but npm is using xxx itself. Use the --scripts-prepend-node-path option to include the path for the node binary npm was executed with.

正如报错指出的,为了修正这个问题,需要用到 scripts-prepend-node-path。这样,当 npm 需要 Node.js 来执行代码的时候,会选择和自身匹配的 Node.js 版本,而不是默认 path 上的版本。(文档

除了每次运行时加上命令行参数之外,一个比较简单的方法是使用 npm config 设置相对应的参数:

npm config set scripts-prepend-node-path=true

或是在 .npmrc 中加上

scripts-prepend-node-path true

设置完后,就不会再有报错了。