Is it possible to use npm to run scripts in multip

2019-03-18 06:36发布

问题:

I have a folder (a project) with 3 subfolders (client, server, assets). Each subfolder has a different command to start and to work on the project I need to start the 3 apps. This is the folder layout and the commands I use to start each subproject:

  • project
    • client (ionic serve)
    • server (node index)
    • assets (http-server -p 8082)

Currently, I go to each of the three folders and start each of the apps. To make the process more standard, each subproject has a package.json with a start script, so I just cd subfolder && npm start.

My question: is it possible to use npm on the parent folder (i.e., write a package.json there) in such a way that I can just run the following command and have the same (or similar) effect?

project> npm start

I have tried using the package parallelshell, but it didnt work (probably because of the cd:

"scripts": {
  "start": "parallelshell 'cd app && ionic serve' 'cd api && npm start' 'cd assets && npm start'",
}

回答1:

You can use "concurrently" to accomplish this. So you would create a package.json which looks something like the following:

...
"scripts": {
  "client": "cd client && npm start",
  "server": "cd server && npm start",
  "assets": "cd assets && ionic serve",
  "start": "concurrently \"npm run client\" \"npm run server\" \"npm run assets\" ",
},
...
"devDependencies": {
  "concurrently": "^1.0.0"
}
...

Note: This will start all three processes concurrently which means that you get mixed Output of all three (like topheman already mentioned)



回答2:

The problem is that all your three scripts are server launching-like script task, which means that they're not like a build task (for example) that runs for 10s and stop the process.

For each one of them, you launch them, and the process continues indefinitly.

You could launch all of them in a daemon way with something like forever, but in your case, you are in dev mode (so you want all the logs, and you don't want the errors from the nodejs server mixed with the ionic one ...).

In case you don't mind about mixing logs: https://www.npmjs.com/package/forever (I assume this does nearly the same thing as parallelshell ...)



标签: npm