React nested route fails to load on refresh

后端 未结 3 1001
清酒与你
清酒与你 2021-02-03 10:44

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

相关标签:
3条回答
  • 2021-02-03 11:05

    @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'
        },
        ...
    }
    
    0 讨论(0)
  • 2021-02-03 11:11

    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 - OK
    0 讨论(0)
  • 2021-02-03 11:11

    For 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',
      },
    
    0 讨论(0)
提交回复
热议问题