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

前端 未结 3 1149
我在风中等你
我在风中等你 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:24

    Note: This answer works on all platforms.

    npm i -g mocha

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

    Mocha CLI documentation (scroll to usage section).


    If you want to run an npm package as an executable from the CLI, the right way to do it is via the package.json bin entry. It allows you to map files in your project as executables. The first line of the files, like normal scripts should start with a shebang, #!/usr/bin/env node if it's a node script.

    By mapping these files in your package.json bin, you will be able to call them from other packages scripts section, or call them from the cli when your package is installed globally with npm install -g . The bin node can be an object that maps script names to script files within your project if you want to add multiple scripts to your path as executables, or a string path of a single file that you would like to act as the executable for your package.

    This is in fact the exact same mechanism used by mocha in your example:

    Without this, mocha would never be in your path when installing it globally, and would not be accessible via your scripts section.

提交回复
热议问题