How to use executables from a package installed locally in node_modules?

前端 未结 22 2082
时光说笑
时光说笑 2020-11-22 12:40

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
22条回答
  •  青春惊慌失措
    2020-11-22 13:04

    Add this script to your .bashrc. Then you can call coffee or anyhting locally. This is handy for your laptop, but don't use it on your server.

    DEFAULT_PATH=$PATH;
    
    add_local_node_modules_to_path(){
      NODE_MODULES='./node_modules/.bin';
      if [ -d $NODE_MODULES ]; then
        PATH=$DEFAULT_PATH:$NODE_MODULES;
      else
        PATH=$DEFAULT_PATH;
      fi
    }
    
    cd () {
      builtin cd "$@";
      add_local_node_modules_to_path;
    }
    
    add_local_node_modules_to_path;
    

    note: this script makes aliase of cd command, and after each call of cd it checks node_modules/.bin and add it to your $PATH.

    note2: you can change the third line to NODE_MODULES=$(npm bin);. But that would make cd command too slow.

提交回复
热议问题