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

6
我使用webpack构建代码块,以便按需加载(代码分割);每个代码块将React组件渲染到DOM元素(div)中。我需要HTML来创建这些div:应该如何加载相应的HTML?以及应该如何按需加载代码块?
我使用jQuery的load函数将文件中的HTML插入到容器div中。此外,我还添加了一个

你是在谈论服务器端渲染的HTML吗?我认为通常情况下,与库代码相比,组件添加的几千字节的代码不值得拆分成块。你看到了巨大的大小差异吗? - Christian Steinmann
在客户端上,加载时间的差异可以看出来:应用程序的某些部分仅在需要时加载。但我同意这并没有太大的区别 - 至少在我的情况下。 - mguijarr
2个回答

2

对于动态路由加载,您应该使用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);
      }
    }
  ]
};

你可以在这篇博客文章中获取整个指南:React Router自动代码拆分

0
原来我想要实现的功能可以通过 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,设计是每个部分都是一个组件。在此示例中,只需激活链接到#/otherpath即可使other组件作为上级组件(名为app的路由)的子级加载。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接