How does npm start work? What all processes are happening in the background?

An npm script is just a shortcut to run a series of node commands on your project. Any npm script, meaning any node.js commands listed under a package.json file’s “scripts” section, are executed through node.js when you call them. So npm start runs the node script that is listed under start in the package.json. As in the article that cbr mentioned in a comment, in the case of create-react-app, this happens:

A new instance of the WebpackDevServer from the library of the same name is created, passing in the compiler and configuration. Webpack is run here by the WebpackDevServer. A listener method on the instance is called, passing in the port and host values. This then clears the console and puts up the text “ Starting the development server…”. The browser is opened with the correct dev URL. Lastly, two listeners are added for when the process is killed, which turns off the web server, and exits the start.js process.

That’s a great article @cbr linked and highly recommended. But that is just for CRA. If you are setting up a react project from scratch (highly recommended if you are just starting to learn all this stuff), your start script might look like this:

"start": "webpack-dev-server --mode development --open"

This tells webpack to spin up a development server, serve the files live, and open the browser to the port you specify in the webpack.config file (or it will use the default 8080). If you already ready to build your project for final deployent, you would write a build script and run npm run build. It might look like this:

"build": "webpack --mode production"

Learning about webpack will help you understand what’s happening under the hood with most react projects. Hope that helps, and thanks @cbr.

Leave a Comment