search

Home  >  Q&A  >  body text

React build will not work properly without adding index.html in URL

<p>I'm using hash routing for a React JS application. The application runs fine in local environment. </p> <p>For example https://stackoverflow.com/posts/ should be the URL of the application but it doesn't work and I have to use https://stackoverflow.com/posts/index.html to make it work. </p> <p>After deploying, I noticed that it was downloading an empty file named "<strong>download</strong>" instead of serving the default <strong>index.html</strong> file in the build file . To run builds on the server, I use S3 and CloudFront architecture. </p> <p>Right now, I can't tell if the HASH routing is misbehaving or if there's something wrong with the AWS deployment. </p> <p>Code snippet using React JS</p> <pre class="brush:php;toolbar:false;">import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './redux/store'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { HashRouter } from 'react-router-dom/cjs/react-router-dom'; ReactDOM.render( <Provider store={store}> <HashRouter> <App /> </HashRouter> </Provider> document.getElementById('root') );</pre> <p><strong>Part of package.json content</strong></p> <pre class="brush:php;toolbar:false;">{ "name": "loremipsum", "version": "0.1.0", "private": true, "homepage": "/loremipsum/" }</pre></p>
P粉216203545P粉216203545455 days ago474

reply all(1)I'll reply

  • P粉515066518

    P粉5150665182023-09-02 00:44:52

    Does it need to be deployed in a subdirectory? If so, you will have to change the contents of the package.json file to force the resource to be served relative to the index.html file.

    {
      "name": "loremipsum",
      "version": "0.1.0",
      "private": true,
      "homepage": ".",
      "scripts": {
        "build": "react-scripts build",
        "build-prd": "PUBLIC_URL=http://www.foo/relativepath react-scripts build"
        // ...
      }
    }
    

    With this we will be able to move applications hosted in http://www.foo to http://www.foo/relativepath or even https://www.foo/bar1/bar2/ No need to rebuild.

    You must also override PUBLIC_URL to include the domain and subdirectory where you want the files to be hosted

    reply
    0
  • Cancelreply