1

在 react router v3 中,我已经使用 实现了代码拆分System.import,现在我想将我的应用程序升级到 react-router-v4,但问题是我无法拆分我的代码。

我的routes.js档案

function errorLoading(error) {
  throw new Error(`Dynamic page loading failed: ${error}`);
}

function loadRoute(cb) {
  return module => cb(null, module.default);
}

module.exports = {
  path: '/',
  indexRoute: {
    getComponent(location, cb) {
      System.import('../pages/IndexPage')
        .then(loadRoute(cb))
        .catch(errorLoading);
    }
  },
  childRoutes: [{
    path: 'notifications',
    indexRoute: {
      getComponent(location, cb) {
        System.import('../pages/NotificationPage')
          .then(loadRoute(cb))
          .catch(errorLoading);
      }
    },
  }]
};

然后我只是在我的index.js文件中导入路由并将它们呈现给 rootNode 就像

ReactDOM.render(
  <AppContainer>
    <ApolloProvider store={store} client={client}>
      <Router
        history={browserHistory}
        routes={routes}
      />
    </ApolloProvider>
  </AppContainer>,
  rootNode
);
4

3 回答 3

2

查看react-async-component。它对我的hapi-react-hot-loader-example非常有用

import {asyncComponent} from 'react-async-component';

export default asyncComponent({
    name: 'AboutAsync',
    serverMode: 'resolve',
    resolve: () => import(/* webpackChunkName: "About" */ './About'),
});

在路由器中:

<Route
    path="/about"
    component={AboutAsync}
/>
于 2017-09-07T15:03:06.593 回答
0

如果您可以使用 ES6 动态导入,则可以使用react-loadable并以这种方式实现代码拆分:

export const AsyncComponent = Loadable({
  loader: () => import(/* webpackChunkName: "name" */ 'path/to/Component'),
  loading: () => null
})

// ...
<Route path='some/path' component={AsyncComponent} />
于 2017-08-11T13:33:47.173 回答
0

通过简单地添加路线来做到这一点

<Route
  name="landing"
  path="/"
  getComponent={
    (_, cb) => import('./pages/LandingPage/LandingPage' /* webpackChunkName: 'landing' */)
      .then((module) => cb(null, module.default))
      .catch((error) => cb(error, null))
  }
</Route>

永远不要忘记CommonsChunkPlugin在你的webpack.js

于 2017-09-15T19:33:31.363 回答