npm 脚本如何优先考虑本地依赖而不是全局依赖?

How does npm scripts prioritise local dependency over global ones?

我知道 npm 脚本将 ./node_modules/.bin 添加到您的 PATH,因此您可以简单地 运行 npm test 使用下面的 package.json,npm 会自动使用 ./node_modules/.bin

中的本地版本的 mocha
"scripts": {
    "test": "mocha"
}

这是一个很好的功能,因为它让我不用像这样编写 package.json 个文件:

"scripts": {
    "test": "./node_modules/.bin/mocha"
}

但是,如果我引入一个在全球范围内安装了 mocha 的新开发人员怎么办?或者我需要将其推送到具有预配置全局包的环境中?如果我在我的 package.json 中使用简写 mocha,而不是 ./node_modules/.bin/mocha,优先级是全局包还是本地包?

Node.js 将首先尝试 运行 your locally installed packages

If you require a module, Node.js looks for it by going through all node_modules/ directories in ancestor directories (./node_modules/, ../node_modules/, ../../node_modules/, etc.). The first appropriate module that is found is used.

有关 Node.js 如何解析所需模块的更详细说明,here is a nice breakdown