2

I know that it is not possible to serve a react app, using live server. In other words, even though the js is bundled and linked to the HTML file, if you open the file statically, the react code will not render.

I read about static and dynamic servers, but since React happens all on client side, I cannot understand why serving the app using webpack, vite or even a simple express server works, but it cannot be served through a server like live server, or opened manually and work.

What is the difference?

noviceGuru
  • 125
  • 1
  • 6
  • If by *live server* you mean the [live-server](https://www.npmjs.com/package/live-server) then it's perfectly fine to run react apps with it. You just run the `live-server` in your app directory, open your browser and navigate to `http://localhost:8080/app.html` (or whatever other page your app is in). As for opening the page directly from the file system, it's true, it doesn't work. Your question has then two facts, you claim that the app doesn't work when run on live-server and when run when opened directly in the browser. The first fact is false, the second is true. – Wiktor Zychla Feb 02 '23 at 08:17
  • You're right, I had to specify that by live-server, I meant live-server extension of vs code. Do you have any insights on that? – noviceGuru Feb 03 '23 at 08:05

1 Answers1

1

The difference is in how the JavaScript code is executed in the browser. When you serve your React app through a webpack dev server, an express server, or any other kind of server, the JavaScript code is executed in the context of a web page, with access to the DOM and all the Web APIs.

But when you open an HTML file statically, the JavaScript code is executed in an isolated environment, with limited access to the Web API. This is why React code that relies on the DOM and Web API will not work when opened manually.

Webpack, vite, and express provide a dynamic environment with all the necessary APIs and services that React needs to run properly. This is done by serving the app as a web page over HTTP, which the browser then loads and executes.

sm3sher
  • 2,764
  • 1
  • 11
  • 23