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

npm install coffee-script

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

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


当前回答

我提出了一个我已经开发的新解决方案(05/2021)

您可以使用lpx https://www.npmjs.com/package/lpx来

运行本地node_modules/.bin文件夹中的二进制文件 在工作空间的任何地方运行工作空间根目录的node_modules/.bin中的二进制文件

如果在本地找不到二进制文件,LPX不会下载任何包(即不像npx)

例子: LPX TSC -b -w将与本地typescript包一起运行TSC -b -w

其他回答

我一直使用与@guneysus相同的方法来解决这个问题,即在包中创建一个脚本。Json文件,并使用它运行NPM run script-name。

然而,最近几个月我一直在使用npx,我很喜欢它。

例如,我下载了一个Angular项目,但我不想全局安装Angular CLI。所以,在安装了npx之后,不用使用angular cli的全局命令(如果我已经安装了它),就像这样:

ng serve

我可以从控制台这样做:

npx ng serve

这是我写的一篇关于NPX的文章,更深入地讨论了它。

更新:如果你在最近的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

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

包中包括咖啡脚本。Json和每个项目所需的特定版本,通常如下所示:

"dependencies":{
  "coffee-script": ">= 1.2.0"

然后运行npm install在每个项目中安装依赖项。这将安装指定版本的coffee-script,每个项目都可以在本地访问该版本。

使用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