简体   繁体   中英

React Route Splitting Code cannot load chunk

i try to forwards React Route Huge App Example . But, after webpack splitting code, always load chunk with 404.

Here is my Router.

<Router history={appHistory} >
  <Route path='/' component={RootContainer}>
    <IndexRoute component={MainContainer}></IndexRoute>
    <Route path='/demo1' getComponent={(location, cb) => {
      require.ensure([], require => {
        cb(null, require('../../components/container/DemoContainer1.jsx').default);
      });
    }}/>
    <Route path='/message/:id' getComponent={(location, cb) => {
        require.ensure([], require => {
          cb(null, require('../../components/container/DemoContainer5.jsx').default);
        });
      }}>
    </Route>
  </Route>
</Router>

Then i click the following link

 <Link to='/message/3'>Go</Link>

i switch to Dev Tool, i found that it load http:/localhost:8080/message/10.chunk.js

so that, it cause 404. Anyone know how to config the Route Config to make the splitting code correctly?

Finally, i found the solution.

webpack.config.js

output: {
  path: __dirname + '/client/src/assets',
  filename: '[name].js',
  chunkFilename: '[id].chunk.js',
  publicPath: '/__build__/'
},
debug: true,
devtool: 'source-map',
devServer: {
  inline:true,
  contentBase: __dirname + '/client/src/assets',
  port: 3333,
  host: '127.0.0.1',
  historyApiFallback: true,
  publicPath: '/__build__/'
},

Need to define the publicPath. Then webpack will base on the publicPath to load resource.

seems like there is a bug being fixed on react router example where taion says call getComponent with nextState instead instead of location on your Routes this should be

    <Router history={appHistory} >
  <Route path='/' component={RootContainer}>
    <IndexRoute component={MainContainer}></IndexRoute>
    <Route path='/demo1' getComponent={(nextState, cb) => {
      require.ensure([], require => {
        cb(null, require('../../components/container/DemoContainer1.jsx').default);
      });
    }}/>
    <Route path='/message/:id' getComponent={(nextState, cb) => {
        require.ensure([], require => {
          cb(null, require('../../components/container/DemoContainer5.jsx').default);
        });
      }}>
    </Route>
  </Route>
</Router>

just check the link that you referred to in your question

where the nextState is a type RouterState

  type RouterState = {
location:Location,
routes: Array<Route>,
params: Params,
components:Array<Component>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM