如何在node.js中使用一个模块的本地版本。例如,在我的应用程序中,我安装了coffee-script:
npm install coffee-script
这会将其安装在。/node_modules中,而coffee命令则安装在。/node_modules/.bin/coffee中。当我在项目的主文件夹中时,是否有一种方法可以运行此命令?我想我在寻找类似于捆绑执行者的东西。基本上,我想指定一个参与项目的每个人都应该使用的coffee-script版本。
我知道我可以添加-g标志来在全球范围内安装它,这样咖啡在任何地方都可以正常工作,但是如果我想在每个项目中使用不同版本的咖啡呢?
如果你想让你的PATH变量根据你当前的工作目录正确地更新,把它添加到你的.bashrc等价文件的末尾(或者任何定义PATH的东西之后):
__OLD_PATH=$PATH
function updatePATHForNPM() {
export PATH=$(npm bin):$__OLD_PATH
}
function node-mode() {
PROMPT_COMMAND=updatePATHForNPM
}
function node-mode-off() {
unset PROMPT_COMMAND
PATH=$__OLD_PATH
}
# Uncomment to enable node-mode by default:
# node-mode
这可能会在每次呈现bash提示符时增加一个短延迟(很可能取决于项目的大小),因此默认情况下禁用它。
您可以在终端中通过分别运行node-mode和node-mode-off来启用和禁用它。
更新:正如Seyeong Jeong在他们的回答中指出的那样,从npm 5.2.0开始,你可以使用npx[命令],这更方便。
5.2.0之前版本的旧答案:
放置的问题
./node_modules/.bin
只有当你的当前工作目录是你的项目目录结构的根目录(即node_modules的位置)时,它才有效。
不管您的工作目录是什么,您都可以使用
npm bin
要执行本地安装的coffee二进制文件,而不依赖于项目目录层次结构中的位置,可以使用这个bash构造
PATH=$(npm bin):$PATH coffee
我把它别名为npm-exec
alias npm-exec='PATH=$(npm bin):$PATH'
现在我可以了
npm-exec coffee
无论我在哪里都能正确地运行咖啡
$ pwd
/Users/regular/project1
$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee
$ cd lib/
$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee
$ cd ~/project2
$ npm-exec which coffee
/Users/regular/project2/node_modules/.bin/coffee
如果您正在使用fish shell,并且出于安全原因不想添加到$path。我们可以添加下面的函数来运行本地节点可执行文件。
### run executables in node_module/.bin directory
function n
set -l npmbin (npm bin)
set -l argvCount (count $argv)
switch $argvCount
case 0
echo please specify the local node executable as 1st argument
case 1
# for one argument, we can eval directly
eval $npmbin/$argv
case '*'
set --local executable $argv[1]
# for 2 or more arguments we cannot append directly after the $npmbin/ since the fish will apply each array element after the the start string: $npmbin/arg1 $npmbin/arg2...
# This is just how fish interoperate array.
set --erase argv[1]
eval $npmbin/$executable $argv
end
end
现在你可以这样运行:
n咖啡
或者更多像这样的论点:
N浏览器同步——版本
注意,如果您是bash用户,则可以使用bash的$@来回答@ bob9630,这在fishshell中是不可用的。
使用npm run[-script] <脚本名>
使用npm将bin包安装到本地的。/node_modules目录后,修改package。Json添加<脚本名称>,如下所示:
$ npm install --save learnyounode
$ edit packages.json
>>> in packages.json
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"learnyounode": "learnyounode"
},
...
$ npm run learnyounode
如果npm install有——add-script选项之类的,或者如果npm run不添加脚本块也能正常工作,那就太好了。