20

I am new to create-react-app. I want to know why opening the index.html form a build does not work ?? I know to serve a build serve -s build should be used, but I want to know why a build react app can’t be started without serving.

I will explain further: What I do is...

  1. create-react-app helloworld
  2. Make some code changes and verify that app is running ok.
  3. npm run build or yarn run build ... Now I will have my ./build directory created with index.html in it.
  4. Now I just open index.html in browser and it won't work.

I want to understand why this does not work? Why I have to serve the build to make it work?

Gaurav51289
  • 540
  • 2
  • 7
  • 16

3 Answers3

13

Following answer was given on similar topic by some guy on reddit

The project was built assuming it is hosted at the server root.

To override this, specify the homepage in your package.json.

I wouldn't recommended it but you can add the following to package.json to run it directly from your file server -

"homepage":"./"

https://www.reddit.com/r/reactjs/comments/5iya27/why_open_up_indexhtml_wont_workcreatereactapp/

also, You may want so serve the app on some kind of server more info here: https://create-react-app.dev/docs/deployment and here: https://create-react-app.dev/docs/production-build

Marek Kamiński
  • 409
  • 5
  • 11
4

For those using react-router-dom, you can use <HashRouter> instead of <BrowserRouter>. It should look like this:

<HashRouter>
  <Switch>
    <Route path="/" exact component={ Main } />
  </Switch>
</HashRouter>
ChechoCZ
  • 304
  • 4
  • 12
  • 1
    Thanks man, Works for me. [Here](https://stackoverflow.com/a/51976069/6585476) are a useful resource about the difference between `BrowserRouter` and `HashRouter` – Budi Salah Aug 10 '21 at 06:03
1

For react-router apps, there is a hack. Just make a <Route/> with path "/index.html" going to a suitable component.

<Route exact path="/" component={Home} /> <Route path="/index.html" component={Home} />

Ankit Topno
  • 375
  • 2
  • 3