详解webpack + react + react-router 如何实现懒加载(2)
这样看起来是不是简洁了很多
注意: 由于webpack的原因, 如果直接require('./AboutPage.jsx')不能正常加载, 请尝试require('./AboutPage.jsx').default
webpack2 代码分割
上面的代码看起来好像都是webpack1的写法, 那么webpack2呢?
webpac2就需要借助System.import了
export default function({history}) { return ( <Router history={history}> <Route path="/" getComponent={(location, callback) => { System.import('./HomePage.jsx').then(component => { callback(null, component.default || component) }) }} /> <Route path="/about" getComponent={(location, callback) => { System.import('./AboutPage.jsx').then(component => { callback(null, component.default || component) }) }} /> </Router> ) }
我们一样可以把上面的代码优化一下
const home = (location, callback) => { System.import('./HomePage.jsx').then(component => { callback(null, component.default || component) }) } const about = (location, callback) => { System.import('./AboutPage.jsx').then(component => { callback(null, component.default || component) }) } export default ({ history }) => { return ( <Router history={history}> <Route name="home" path="/" getComponent={home} /> <Route name="about" path="/about" getComponent={about} /> </Router> ) }
webpack2 + dva 实现路由和 models 懒加载
const routerThen = (app, callback, [component, model]) => { app.model(model.default || model) callback(null, component.default || component) } export default ({ history, app }) => { return ( <Router history={history}> <Route name="home" path="/" getComponent={(location, callback) => { Promise.all([ System.import('./views/app.jsx'), System.import('./models/topics') ]).then(routerThen.bind(null, app, callback)) }} /> <Route name="article" path="/article/:id" getComponent={(location, callback) => { Promise.all([ System.import('./views/article.jsx'), System.import('./models/topic') ]).then(routerThen.bind(null, app, callback)) }} /> </Router> ) }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。