如何在node.js中使用一个模块的本地版本。例如,在我的应用程序中,我安装了coffee-script:

npm install coffee-script

这会将其安装在。/node_modules中,而coffee命令则安装在。/node_modules/.bin/coffee中。当我在项目的主文件夹中时,是否有一种方法可以运行此命令?我想我在寻找类似于捆绑执行者的东西。基本上,我想指定一个参与项目的每个人都应该使用的coffee-script版本。

我知道我可以添加-g标志来在全球范围内安装它,这样咖啡在任何地方都可以正常工作,但是如果我想在每个项目中使用不同版本的咖啡呢?


当前回答

使用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不添加脚本块也能正常工作,那就太好了。

其他回答

使用npm bin命令获取项目的节点模块/bin目录

$ $(npm bin)/<binary-name> [args]

e.g.

$ $(npm bin)/bower install

我是一个Windows用户,这对我来说是有效的:

// First set some variable - i.e. replace is with "xo"
D:\project\root> set xo="./node_modules/.bin/"

// Next, work with it
D:\project\root> %xo%/bower install

祝你好运。

如果您正在使用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中是不可用的。

你不必再操纵$PATH了!

从npm@5.2.0, npm附带了npx包,它可以让你从本地node_modules/.bin或中央缓存运行命令。

简单地运行:

$ npx [options] <command>[@version] [command-arg]...

默认情况下,npx将检查<命令>是否存在于$PATH或本地项目二进制文件中,并执行它。

当<命令>不在$PATH中时调用npx <命令>将自动从NPM注册表中为你安装一个带有该名称的包,并调用它。当它完成时,安装的包将不会在你的全局包的任何地方,所以你不必担心长期的污染。你可以通过提供——no-install选项来防止这种行为。

对于npm < 5.2.0,您可以通过执行以下命令手动安装npx包:

$ npm install -g npx

我遇到了同样的问题,我不特别喜欢使用别名(正如常规的建议),如果你也不喜欢它们,那么这里有另一个我使用的解决方案,你首先必须创建一个小的可执行bash脚本,说setenv.sh:

#!/bin/sh

# Add your local node_modules bin to the path
export PATH="$(npm bin):$PATH"

# execute the rest of the command
exec "$@"

然后,您可以使用以下命令使用本地/bin中的任何可执行文件:

./setenv.sh <command>
./setenv.sh 6to5-node server.js
./setenv.sh grunt

如果你在包中使用脚本。json:

...,
scripts: {
    'start': './setenv.sh <command>'
}