Gaurav51289
Gaurav51289

Reputation: 570

Why running index.html won't work for a `create-react-app` build?

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?

Upvotes: 22

Views: 20933

Answers (3)

ChechoCZ
ChechoCZ

Reputation: 312

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>

Upvotes: 4

Marek Kamiński
Marek Kamiński

Reputation: 442

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

Upvotes: 13

Ankit Topno
Ankit Topno

Reputation: 385

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} />

Upvotes: 1

Related Questions