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

前端 未结 22 1919
时光说笑
时光说笑 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:16

    You can also use direnv and change the $PATH variable only in your working folder.

    $ cat .envrc
    > export PATH=$(npm bin):$PATH
    
    0 讨论(0)
  • 2020-11-22 13:19

    Use npm-run.

    From the readme:

    npm-run

    Find & run local executables from node_modules

    Any executable available to an npm lifecycle script is available to npm-run.

    Usage

    $ npm install mocha # mocha installed in ./node_modules
    $ npm-run mocha test/* # uses locally installed mocha executable 
    

    Installation

    $ npm install -g npm-run
    
    0 讨论(0)
  • 2020-11-22 13:19

    In case you are using fish shell and do not want to add to $path for security reason. We can add the below function to run local node executables.

    ### 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
    

    Now you can run thing like:

    n coffee

    or more arguments like:

    n browser-sync --version

    Note, if you are bash user, then @Bob9630 answers is the way to go by leveraging bash's $@, which is not available in fishshell.

    0 讨论(0)
  • 2020-11-22 13:21

    You don't have to manipulate $PATH anymore!

    From npm@5.2.0, npm ships with npx package which lets you run commands from a local node_modules/.bin or from a central cache.

    Simply run:

    $ npx [options] <command>[@version] [command-arg]...
    

    By default, npx will check whether <command> exists in $PATH, or in the local project binaries, and execute that.

    Calling npx <command> when <command> isn't already in your $PATH will automatically install a package with that name from the NPM registry for you, and invoke it. When it's done, the installed package won’t be anywhere in your globals, so you won’t have to worry about pollution in the long-term. You can prevent this behaviour by providing --no-install option.

    For npm < 5.2.0, you can install npx package manually by running the following command:

    $ npm install -g npx
    
    0 讨论(0)
提交回复
热议问题