Multiple commands in package.json

This command: "start": "node server/server.js" starts my server, but before running this I also want a command to run automatically: 'webpack'.

I want to build a script that can be run with npm run someCommand - it should first run webpack in the terminal, followed by node server/server.js.

(I know how configure this with gulp, but I don't want to use it)

83776 次浏览

If I understood you correctly, you want firstly run webpack and after compile run nodejs. Maybe try this:

"start": "webpack && node server/server.js"

The following should work:

"start": "webpack && node server/server.js"

Though, for readability (and especially if you plan on adding additional tasks in the future), you may want to consider creating separate entries for each task and then calling each of those from start. Something like:

{
"init-assets": "webpack",
"init-server": "node server/server.js",
"start": "npm run init-assets && npm run init-server"
}

You can also chain commands like this:

"scripts": {
"clean": "npm cache clean --force",
"clean:complete": "npm run clean && npm uninstall -g @angular/cli && rmdir /Q /S node_modules",
"clean:complete:install": "npm run clean:complete && npm i -g @angular/cli && npm i && npm install --save-dev @angular/cli@latest"
}

Also, along with the accepted answer and @pdoherty926's answer, in case you want to have run two command prompts, you can add "start" before each command:

{
"init-assets": "webpack",
"init-server": "node server/server.js",
"start": "start npm run init-assets && start npm run init-server"
}

Better understand the && operator

In my case the && didn't work well because one of my commands sometimes exited with non zero exit code (error) and the && chaining operator works only if the previous command succeeds.

The main chaining operators behave like this:

  • && runs the next command only if the first succeeds (AND)
  • || runs the next command only if the first fails (OR)

So if you want the second command to run whatever the first has outputted the best way is to do something like (command1 && command2) || command 2

Others OS specific chaining operators

Other separators are different in a Unix (linux, macos) and windows environnement

  • ; UNIX run the second command whatever the first has outputted
  • ; WIN separate command arguments
  • & UNIX run first command in the background parallel to the second one
  • & WIN run the second command whatever the first has outputted

All chaining operators for windows here and for unix here