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

npm install coffee-script

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

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


当前回答

ZXC就像nodejs的“bundle exec”。类似于使用PATH=$(npm bin):$PATH:

$ npm install -g zxc
$ npm install gulp
$ zxc which gulp
/home/nathan/code/project1/node_modules/.bin/gulp

其他回答

如果你想保留npm,那么npx应该做你所需要的。


如果切换到yarn (facebook的npm替代品)是你的一个选择,那么你可以调用:

 yarn yourCmd

包中的脚本。Json将优先,如果没有找到,它将在./node_modules/.bin/文件夹中查找。

它还输出它运行的内容:

$ yarn tsc
yarn tsc v0.27.5
$ "/home/philipp/rate-pipeline/node_modules/.bin/tsc"

因此,您不必为package.json中的每个命令设置脚本。


如果你在package.json中有一个定义在.scripts的脚本:

"tsc": "tsc" // each command defined in the scripts will be executed from `./node_modules/.bin/` first

纱线TSC相当于纱线运行TSC或NPM运行TSC:

 yarn tsc
 yarn tsc v0.27.5
 $ tsc

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

TL;DR:使用npm exec与npm@>=7。


在其他回答中提到的npx命令已经在npm@7中完全重写,该命令默认与node@15一起发布,可以安装在node@>=10上。这个实现现在等于新引入的npm exec命令,它类似于之前的npx命令实现,但不等于。

一个不同之处在于,当一个依赖项还没有安装时,它总是交互式地询问是否应该下载它(也可以用参数——yes或——no来覆盖)。

这里有一个npm exec的例子。双破折号(——)将npm exec参数与实际的命令参数分开:

npm exec --no -- jest --coverage

请参见更新后的npm exec官方文档。

我不喜欢依赖shell别名或其他包。

向包的脚本部分添加简单的一行。Json,你可以运行本地NPM命令像

pm网络包装

package.json

{
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack"
  },
  "devDependencies": {
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.11"
  }
}

相同的@常规的接受方案,但鱼壳味

if not contains (npm bin) $PATH
    set PATH (npm bin) $PATH
end