How can I run multiple npm scripts in parallel?

后端 未结 22 2124
灰色年华
灰色年华 2020-11-22 05:48

In my package.json I have these two scripts:

  \"scripts\": {
    \"start-watch\": \"nodemon run-babel index.js\",
    \"wp-server\": \"webpack-         


        
22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:26

    Quick Solution

    In this case, I'd say the best bet If this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this: &

    An example of doing this in a partial package.json file:

    {
      "name": "npm-scripts-forking-example",
      "scripts": {
        "bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
        "serve":  "http-server -c 1 -a localhost",
        "serve-bundle": "npm run bundle & npm run serve &"
      }
    

    You'd then execute them both in parallel via npm run serve-bundle. You can enhance the scripts to output the pids of the forked process to a file like so:

    "serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",
    

    Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:

    Further Context RE: Unix Tools & Node.js

    If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:

    1. Much of Node.js lovingly imitates Unix principles
    2. You're on *nix (incl. OS X) and NPM is using a shell anyway

    Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs to streams.

提交回复
热议问题