As there is no straightforward way provided by npm to run multiple scripts in parallel, We can try coming up with a solution in the following way:
Create a basic React App project on the Localhost server and at the same time, we want to run the build operation of the project. Now what we can do is we can make use of the npm-run-all package, which will make it easy for us to host the project on the Localhost server, and also we can run the optimized build for production simultaneously.
Approach 1(npm-run all package): We can use the” npm-run all” package to run different scripts at the same time. First, we have to install the package itself by using the command.
npm install npm-run-all — save-dev
After installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build” that we need in order to host the project on the server and to run the build operation simultaneously.
Now, our next step would be to open up a terminal on Mac or command prompt on Windows and “cd” into the project directory and type the command “./node_modules/.bin/npm-run-all build start ” and press Enter.
In the local installation case which we did, npm-run-all will be installed into our project’s node_modules
directory. PATH environment variable does not include there, so we have to use
./node_modules/.bin/npm-run-all (or $(npm bin)/npm-run-all) to run npm-run-all command.
Therefore, we can now see that our app is successfully hosted on a local server, and the build operation executed perfectly with the help of a single package “npm-run-all”.
Approach 2 (Using Concurrently package): In this approach, we will be using the Concurrently package . Using this package we can combine different script commands such as “npm run start” and “npm run build ” into a single script and then run it in the command line.
First, install the package in your project directory using this command :
npm install concurrently --save
Again after installation of the package we have to navigate to the package.json file of the project, and we can see that there are two operations listed inside the “scripts” i.e “start” & “build” that we need in order to host the project on the server and to run the build operation simultaneously.
Now we have to include a dev script inside the scripts in the package.json file which will hold our different commands combined.
With –kill-others switch, all commands are killed if one dies.
We can follow this to create our own dev script :
"dev": "concurrently \"command1 arg\" \"command2 arg\""
Now we can simply run the whole command by simply using :
npm run dev
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.