Achieve “npm run x” behavior without a “scripts” entry?

前端 未结 3 1142
我在风中等你
我在风中等你 2021-02-05 08:01

To run a node command within the \"context\" of your installed node_modules, you can make an entry in the scripts field of package.json.

3条回答
  •  不思量自难忘°
    2021-02-05 08:41

    Note: This answer addresses the OP's specific use case: calling the CLIs of dependent packages in the context of a given project; it is not about making CLIs globally available - see bottom for a discussion.

    tl;dr:

    On Unix-like platforms, prepend npm run env -- to your command; e.g.:

    npm run env -- mocha --recursive test/**/*.js --compilers js:babel-register
    

    This not only enables calling of dependent CLIs by mere name, but fully replicates the environment that npm sets behind the scenes when you use npm test or npm run-script .

    Sadly, this approach doesn't work on Windows.

    For Windows solutions, convenience aliases (including once-per-session environment-configuration commands), and background information, read on.


    There are two (not mutually exclusive) approaches to making an npm project's dependencies' CLIs callable by mere name from the shell:

    • (a) Use a per-invocation helper command that you pass your commands to.
    • (b) Run a once-per-session command that (temporarily) modifies your environment.

    Frxstrem's helpful answer provides an incomplete solution for (a) on Unix-like platforms; it may, however, be sufficient, depending on your specific needs.
    It is incomplete in that it merely prepends the directory containing (symlinks to) the dependent CLIs to the $PATH, without performing all other environment modifications that happen when you invoke npm test or npm run-script .


    Unix convenience and Windows solutions

    Note that all solutions below are based on npm run env, which ensures that all necessary environment variables are set, just as they are when your run scripts predefined in the project's package.json file with npm test or npm run-script

提交回复
热议问题