℡Wang Yan 2012-03-13 07:31 采纳率: 100%
浏览 738
已采纳

如何使用本地安装的软件包在节点模块?

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

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.

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?

转载于:https://stackoverflow.com/questions/9679932/how-to-use-package-installed-locally-in-node-modules

  • 写回答

22条回答 默认 最新

  • 衫裤跑路 2013-03-01 12:06
    关注

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

    OLD ANSWER for versions before 5.2.0:

    The problem with putting

    ./node_modules/.bin
    

    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
    

    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
    

    I aliased this to npm-exec

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

    So, now I can

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(21条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)