3

create-react-app seems to start localhost server at npm start.

(npx comes with npm 5.2+ and higher, see instructions for older npm versions)

Then open http://localhost:3000/ to see your app.

When you’re ready to deploy to production, create a minified bundle with npm run build.

https://facebook.github.io/create-react-app/docs/getting-started

Why do I need to bring up a server just to run JavaScript?

What are the differences, advantages, and disadvantages of opening the build result file directly in the browser?

Also, is this true for other frameworks regardless of create-react-app?

I read React's repository etc on this issue, but there was no topic on this issue.

  • React code cannot be read by browser it need to be compiled to JS so that browser can understand it. You can open bundled file directly from public folder in browser – Rikin Jun 01 '19 at 01:46
  • This is the path of recent javascript libraries and there are so many details about how they manage and why. Take a look at web-pack and babel it may help. – Afsanefda Jun 01 '19 at 04:51

1 Answers1

4

One of the main advantages to create-react-app starting a localhost server is hot reloading.

When you write most modern JavaScript, including React, your code needs to be transpiled (essentially converted to a different version of JS) before the browser can understand it. This is called the build process, which takes all the files in the src directory and bundles them into a single static JS file.

You could do this manually with npm run build, which creates an index.html that you can open in a browser without running a server. But you have to go through 2 part process to see your changes: rebuild and then reload the browser to see your changes.

create-react-app is built so that it watches for changes in your files, updates the built JS whenever you hit save, and then restarts the server, loading your changes automatically.

By running a server on localhost, create-react-app can update your page instantly every time you save, without you manually rebuilding OR refreshing the page. Hot reloading!

helloitsjoe
  • 6,264
  • 3
  • 19
  • 32
  • I think that hot reloading can be replaced by `browser-sync` and `watch` functions. Is there an advantage to building a local server instead of the existing method of browser-sync + watch? –  Jun 01 '19 at 23:29
  • Yeah, it’s the same idea, `browser-sync` starts a local server too: https://www.browsersync.io/ (see #3 under “Get started in 5 minutes”) – helloitsjoe Jun 02 '19 at 14:36