我使用webpack构建代码块,以便按需加载(代码分割);每个代码块将React组件渲染到DOM元素(div)中。我需要HTML来创建这些div:应该如何加载相应的HTML?以及应该如何按需加载代码块?
我使用jQuery的load函数将文件中的HTML插入到容器div中。此外,我还添加了一个
我使用jQuery的load函数将文件中的HTML插入到容器div中。此外,我还添加了一个
对于动态路由加载,您应该使用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);
}
}
]
};
<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
的路由)的子级加载。