Run npm scripts in parallel

Elijah Manor
InstructorElijah Manor
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

In this lesson we will look at running several npm scripts in parallel. Sometimes you don’t need scripts to be run in series and switching them to run in parallel can increase performance since they are not blocking each other. At the end you need to add a wait command so they can be terminated with ^C

[00:00] In our test script, instead of chaining our scripts together in series -- ESLint, stylelint, and Mocha -- we may want to run them in parallel instead. As it turns out, that's an easy change to make.

[00:13] All we need to do is remove the double ampersands with a single ampersand. That will change the script from running in series to running in parallel. Now if we go to run our script, npm test, it'll run all three scripts, but this time in parallel, although it's a little hard to see that in action since our tests happen to be at the end.

[00:34] Let's go change our scripts up just a little bit so we can see it in action. We're going to move stylelint to the end and then we'll add the --watch to our Mocha to watch the file system for changes. Now let's run our test again and see what happens.

[00:50] You can see that our test finished last even though it was the second sub command in the test. Also, the command is still watching. If I open up one of our unit tests and change one of the assertions and save, you'll notice Mocha is still in watch mode and reran all the tests.

[01:13] However, we still have a problem. Since we kicked off a long-running Mocha process, even if we cancel in our terminal and it looks like it quit, it's still running. If we come up here and save our unit test again, you'll notice that our test kicked back up and ran again.

[01:32] Thankfully, there's an easy fix for this. Let's cancel out again and we'll go back over to our package.json. At the very end we'll add an &wait, which waits for a process to finish, giving us the ability to terminate the process with Control-C. Let's save this, run our tests, and try again. Here we're going to cancel the process, come back over to our tests and save, and sure enough, the test did not run again. Good.