【问题标题】:Code Splitting by using react router v4使用反应路由器 v4 进行代码拆分
【发布时间】:2017-07-01 22:38:04
【问题描述】:

在 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
);

【问题讨论】:

  • 这是一个很棒的视频教程,其中包含代码示例,您可以按照这些示例设置使用 React Router 4+ 的代码拆分youtu.be/j8NJc60H294

标签: webpack-2 react-router-v4 react-router-dom


【解决方案1】:

查看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}
/>

【讨论】:

  • 感谢 codeBelt 它有效,我还找到了一个更好的解决方案,无需使用任何外部包
【解决方案2】:

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

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

// ...
<Route path='some/path' component={AsyncComponent} />

【讨论】:

    【解决方案3】:

    只需添加类似的路线就可以了

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

    永远不要忘记在您的webpack.js 中使用CommonsChunkPlugin

    【讨论】:

    • 新的 webpack v4 弃用了 CommonsChunkPlugin 是否可行?或者更好的说法是,如何用新版本做到这一点
    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2017-10-21
    • 2017-12-06
    • 2018-08-03
    • 2023-03-12
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多