What is "npm run build" in create-react-app?

Ben Porat picture Ben Porat · May 7, 2017 · Viewed 42.6k times · Source

I could not find any explanation regarding the work of "npm run build",

It is simple and easy to use and i get the "build" folder that works great,

But, in create-react-app, what happens exactly behind the scene?

Is it a complete different use of a build tool?

If not, is it utilizing other build tools?

Answer

patrick.1729 picture patrick.1729 · Feb 5, 2018

Developers often break JavaScript and CSS out into separate files. Separate files let you focus on writing more modular chunks of code that do one single thing. Files that do one thing decrease your cognitive load as maintaining them is a quite cumbersome task.

What happens exactly behind the scene?

When it’s time to move your app to production, having multiple JavaScript or CSS files isn’t ideal. When a user visits your site, each of your files will require an additional HTTP request, making your site slower to load. So to remedy this, you can create a “build” of our app, which merges all your CSS files into one file, and does the same with your JavaScript. This way, you minimize the number and size of files the user gets. To create this “build”, you use a “build tool”. Hence the use of npm run build.

As you have rightly mentioned that running the command (npm run build) creates you a build directory. Now suppose you have a bunch of CSS and JS files in your app:

css/
  mpp.css
  design.css
  visuals.css
  ...
js/
  service.js
  validator.js
  container.js
  ...

After you run npm run build your build directory will be:

build/
  static/
    css/
      main.css
    js/
      main.js

Now your app has very few files. The app is still the same but got compacted to a small package called build.

Final Verdict: You might wonder why a build is even worth it, if all it does is save your users a few milliseconds of load time. Well, if you’re making a site just for yourself or a few other people, you don’t have to bother with this. Generating a build of your project is only necessary for high traffic sites (or sites that you hope will be high traffic soon).

If you’re just learning development, or only making sites with very low traffic, generating a build might not be worth your time.