I have a React app with navigation powered by react-router
that I run in development with webpack-dev-server
and the history fallback option enabled. H
@niba's answer perfectly solved my problem. I have been having the problem that when I nest a <Route/>
element inside a component that is already being rendered by a <Route/>
, it will fail to load the script bundle.js when I try to go to a sub-route url. After adding the following in the webpackConfig.json, everything is back to normal.
module.exports = {
...
output: {
path: path.resolve('dist'),
publicPath: '/',
filename: 'bundle.js'
},
...
}
It doesn't work because it can't load your javascript bundle. I'm guessing that the problem is with your path in script tag in HTML. Probably you have specified the path to app.js with dot at the beginning like this one
<script src="./app.js"></script>
, if this is true please remove dot and check if the problem still exists <script src="/app.js"></script>
Let's illustrate what is the difference between ./app.js
and /app.js
Case 1. You are loading page using first level of routes like /
or /intro
./app.js
: HTML tries to load script from http://address/app.js
/app.js
: HTML tries to load script from http://address/app.js
No difference
Case 2. You are loading page using second level of routes /build/pattern
./app.js
: HTML tries to load script from http://address/build/app.js
- doesn't exist/app.js
: HTML tries to load script from http://address/app.js
- OKFor those who have tried the above and stil have issues, I'm using html-webpack-plugin on my webpack configuration, so it injects the bundle inside the HTML with no need to add any script import on index.html
So I removed the following line from my index.html file:
<script src="/bundle.js"></script>
And added the following configuration on webpack plugins section:
// some other imports
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
...
webpack default config
...
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
hash: true,
inject: true,
}),
...
other plugins,
],
}
Just remember to also use the output configuration accordingly to your project, such as mine:
output: {
path: path.resolve(__dirname, 'public'),
publicPath: '/',
filename: 'bundle.js',
},