使用 webpack 代码拆分,如何加载块和 HTML 布局?

using webpack code splitting, how to load chunks and HTML layout?

我使用 webpack 构建块,按需加载(代码拆分);每个块都将 React 组件渲染成 DOM 个元素 (divs)。我需要 HTML 来创建那些 div:我应该如何以及何时加载相应的 HTML ?我应该如何按需加载块?

我使用 jQuery 的 load 函数从容器 divs 中的文件插入 HTML。此外,我放了一个 <script> 标签来告诉应该加载哪个块,但我发现与我的应用程序代码的其余部分相比,它笨拙而且一点也不优雅。

有没有更简单的方法来做到这一点?

原来我想达到的效果可以通过react-router实现,只是我不知道;)

<Route name="app" component={require('./app.jsx')}>
    <Route path="/" name="home" component={require('./homepage-container.jsx')}/>
    <Route path="/otherpath" name="other" component={require('./other.jsx')}/>
    ... add as many routes as wanted
</Route>

jsx 文件按需加载,不需要普通 HTML 正如我使用的 React 设计,每个部分都是一个组件。 在这个例子中,激活 link 到 #/otherpath 就足够了 获取要加载的 other 组件作为上层组件的子组件(名为 app 的路由)。

您应该使用 require.ensure 进行动态路由加载。更好的是,如果您将项目设置为使用 Webpack 2 + Tree shaking,则可以使用 System.import.

方法如下:

import App from 'containers/App';
function errorLoading(err) {
  console.error('Dynamic page loading failed', err);
}
function loadRoute(cb) {
  return (module) => cb(null, module.default);
}
export default {
  component: App,
  childRoutes: [
    {
      path: '/',
      getComponent(location, cb) {
        System.import('pages/Home')
          .then(loadRoute(cb))
          .catch(errorLoading);
      }
    },
    {
      path: 'blog',
      getComponent(location, cb) {
        System.import('pages/Blog')
          .then(loadRoute(cb))
          .catch(errorLoading);
      }
    }
  ]
};

您可以在此博客中获取完整指南 post:Automatic Code Splitting for React Router