React Route Splitting Code无法加载块

时间:2016-05-21 03:52:17

标签: reactjs react-router

我尝试转发React Route Huge App Example。但是,在webpack拆分代码之后,总是用404加载块。

这是我的路由器。

<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>

然后我点击以下链接

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

我切换到Dev Tool,我发现它加载了 http:/ localhost:8080 / message / 10.chunk.js

这样,它会导致404。 任何人都知道如何配置Route Config以正确分割代码?

2 个答案:

答案 0 :(得分:1)

最后,我找到了解决方案。

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__/'
},

需要定义publicPath。然后webpack将基于publicPath加载资源。

答案 1 :(得分:0)

似乎在反应路由器示例中修复了一个错误,其中taion说使用nextState而不是location来调用getComponent 在你的路线上,这应该是

    <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>

只需在问题中检查referred的链接

其中nextState是一个类型RouterState

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