React build will not work properly without adding index.html in URL
P粉216203545
2023-09-01 11:25:58
<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>
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 theindex.html
file.With this we will be able to move applications hosted in
http://www.foo
tohttp://www.foo/relativepath
or evenhttps://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