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

npm install coffee-script

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

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


当前回答

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

其他回答

您也可以使用direnv并仅在您的工作文件夹中更改$PATH变量。

$ cat .envrc
> export PATH=$(npm bin):$PATH

PATH解决方案有一个问题,如果$(npm bin)被放在你的.profile/。Bashrc /etc只计算一次,并且永远被设置到路径第一次计算所在的目录。如果您修改当前路径,那么每次运行脚本时,路径都会增长。

为了解决这些问题,我创建了一个函数并使用它。它不会修改您的环境,使用简单:

function npm-exec {
   $(npm bin)/$@  
}

然后可以像这样使用,而不需要对环境进行任何更改:

npm-exec r.js <args>

对于Windows,使用以下命令:

/* cmd into "node_modules" folder */
"%CD%\.bin\grunt" --version

使用npm-run。

自述:

NPM 运行

从node_modules中查找并运行本地可执行文件

任何npm生命周期脚本可用的可执行文件都可用于npm-run。

使用

$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable 

安装

$ npm install -g npm-run

我是一个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

祝你好运。