36
votes

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?

2
npm run <script-name> is an npm syntax for running project-specific scripts. Those scrips are defined in scripts section` of your package.json file. For more info see npm-scripts docs. Most likely npm run build in create-react-app simply invokes some other build tool like gulp, grunt or webpack. Check your package.json to see the exact command it runs.Leonid Beschastny

2 Answers

40
votes

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.

7
votes

It's briefly explained here: https://github.com/facebookincubator/create-react-app#npm-run-build-or-yarn-build.

It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.

Behind the scenes, it uses babel to transpile your code and webpack as the build tool to bundle up your application.