如何使用本地安装在 node_modules 中的包中的可执行文件? [英] How to use executables from a package installed locally in node_modules?

查看:40
本文介绍了如何使用本地安装在 node_modules 中的包中的可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I use a local version of a module in node.js. For example, in my app, I installed coffee-script:

npm install coffee-script

这会将其安装在 ./node_modules 中,coffee 命令位于 ./node_modules/.bin/coffee 中.当我在项目的主文件夹中时,有没有办法运行此命令?我想我在 bundler 中寻找类似于 bundle exec 的东西.基本上,我想指定参与该项目的每个人都应该使用的咖啡脚本版本.

This installs it in ./node_modules and the coffee command is in ./node_modules/.bin/coffee. Is there a way to run this command when I'm in my project's main folder? I guess I'm looking for something similar to bundle exec in bundler. Basically, I'd like to specify a version of coffee-script that everyone involved with the project should use.

我知道我可以添加 -g 标志来全局安装它,这样咖啡在任何地方都可以正常工作,但是如果我想每个项目有不同版本的咖啡怎么办?

I know I can add the -g flag to install it globally so coffee works fine anywhere, but what if I wanted to have different versions of coffee per project?

推荐答案

UPDATE:正如 Seyeong Jeong 在下面的回答中指出的那样,从 npm 5.2.0 开始,您可以使用 npx [command],更方便.

UPDATE: As Seyeong Jeong points out in their answer below, since npm 5.2.0 you can use npx [command], which is more convenient.

5.2.0 之前版本的旧答案:

推杆的问题

./node_modules/.bin

进入你的 PATH 是它只在你当前的工作目录是你的项目目录结构的根目录时才有效(即 node_modules 的位置)

into your PATH is that it only works when your current working directory is the root of your project directory structure (i.e. the location of node_modules)

与您的工作目录无关,您可以使用

Independent of what your working directory is, you can get the path of locally installed binaries with

npm bin

要执行本地安装的 coffee 二进制文件,而与您在项目目录层次结构中的位置无关,您可以使用此 bash 构造

To execute a locally installed coffee binary independent of where you are in the project directory hierarchy you can use this bash construct

PATH=$(npm bin):$PATH coffee

我将其别名为 npm-exec

I aliased this to npm-exec

alias npm-exec='PATH=$(npm bin):$PATH'

所以,现在我可以

npm-exec coffee

无论我在哪里都能运行正确的咖啡副本

to run the correct copy of coffee no matter of where I am

$ pwd
/Users/regular/project1

$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd lib/
$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd ~/project2
$ npm-exec which coffee
/Users/regular/project2/node_modules/.bin/coffee

这篇关于如何使用本地安装在 node_modules 中的包中的可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆