react-route4 按需加載配置心得
阿新 • • 發佈:2018-06-21
註意 sets ets 參數 default chunk const 新版 XA 本篇文章主要記錄筆者項目中使用 react-route + webpack 做路由按需加載的心得,可能只有筆者一個人看,權當日記了。
很久很久以前,react-route還是2.X和3.X版本的時候,我們是這樣做按需的:
const routes = { path: ‘/‘, component: AppCom, indexRoute: { component: Admin }, childRoutes: [ { path: ‘edit/:id‘, getComponent: (nextState, cb)=> { require.ensure([], (require) => { cb(null, require(‘../entry/admin/edit.jsx‘)) }) } } ] } <Router routes={routes} history={hashHistory} />
由於筆者公司需要做按需加載的項目並不多,所以在很長一段時間裏,筆者對於按需的印象都一直停留在這個階段。 時間到了2018年3月,筆者總算是能用上按需了,這回我們直接上最新版的react-route,版本號4.1.1。 新版的react-route相比老版本,改動的程度很大,require.ensure雖然還能用,但是getComponent卻已經被處理掉了,筆者根據官方文檔摸索了很久,結果官方文檔的案例沒有一個能看的,直到筆者看到了這篇文章:https://www.jianshu.com/p/547aa7b92d8c。 這裏介紹的,就是這篇文章中提到的使用Bundle來做按需的方式。 我們需要引入Bundle.js作為一個加載器,其代碼如下:
import React from ‘react‘; exportdefault class Bundle extends React.Component { constructor(props) { super(props); this.state = { mod: null }; } componentWillMount() { this.load(this.props) } componentWillReceiveProps(nextProps) { if (nextProps.load !== this.props.load) {this.load(nextProps) } } load(props) { this.setState({ mod: null }); props.load().then((mod) => { this.setState({ mod: mod.default ? mod.default : mod }); }); } render() { return this.state.mod ? this.props.children(this.state.mod) : null; } }
配置路由頁部分代碼:
import Bundle from ‘./Bundle‘; const routeObj = { url1:‘url1/url1‘, url2:‘url2/url2‘, url3:‘url3/url3‘, } let components = {}; for(let route in routeObj){ components[route] = (props) => ( <Bundle load={() => import(`../entry/${routeObj[route]}`)}> {(Component) => <Component {...props}/>} </Bundle> ); }
這裏需要註意,import不支持直接使用變量作為參數,webpack官方解釋如下: 也就是說,import後至少要有一部分是真實路徑,所以才有了
import(`../entry/${routeObj[route]}`)}
路由聲明代碼:
<Route exact path="/" component={components.url1}/>
webpack配置:
output: { path: paths.appBuild, filename: ‘[name].bundle.js‘, chunkFilename: ‘[name].bundle.js‘ }
這樣就完成了按需的配置,開發者工具中也能看到按需加載的代碼塊了。 在這裏,我想吟詩一首: 啊~~ 我編不下去了
react-route4 按需加載配置心得