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

npm install coffee-script

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

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


当前回答

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

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

e.g.

$ $(npm bin)/bower install

其他回答

如果你想保留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

我遇到了同样的问题,我不特别喜欢使用别名(正如常规的建议),如果你也不喜欢它们,那么这里有另一个我使用的解决方案,你首先必须创建一个小的可执行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>'
}

我不喜欢依赖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"
  }
}

更新:如果你在最近的npm(版本>5.2)

你可以使用:

npx <command>

NPX在node_modules的.bin目录下查找命令

旧的回答:

对于Windows

将以下内容存储在一个名为npm-exec.bat的文件中,并将其添加到您的%PATH%

@echo off
set cmd="npm bin"
FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET modules=%%i
"%modules%"\%*

使用

然后你就可以用它 Npm-exec <command> <arg0> <arg1>…

例如

要执行本地node_modules目录下安装的wdio,请执行:

npm-exec wdio wdio.conf.js

例如,它将运行。\node_modules\.bin\wdio wdio.conf.js

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

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

e.g.

$ $(npm bin)/bower install