国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解webpack + react + react-router 如何實現懶加載

2024-05-06 15:24:18
字體:
來源:轉載
供稿:網友

在 Webpack 1 中主要是由bundle-loader進行懶加載,而 Webpack 2 中引入了類似于 SystemJS 的System.import語法,首先我們對于System.import的執行流程進行簡單闡述:

    Webpack 會在編譯過程中掃描代碼庫時將發現的System.import調用引入的文件及其相關依賴進行單獨打包,注意,Webpack 會保證這些獨立模塊及其依賴不會與主應用的包體相沖突。 當我們訪問到這些獨立打包的組件模塊時,Webpack 會發起 JSONP 請求來抓取相關的包體。 System.import 同樣也是 Promise,在請求完成之后System.import會將抓取到的模塊作為參數傳入then中的回調函數。 如果我們重復訪問已經加載完畢的模塊,Webpack 不會重復執行抓取與解析的過程。

而 React Router 路由的懶加載實際上分為動態路由與與懶加載兩步,典型的所謂動態路由配置如下:

/** * <Route path="/" component={Core}> *  <IndexRoute component={Home}/> *  <Route path="about" component={About}/> *  <Route path="users" component={Users}> *  <Route path="*" component={Home}/> * </Route> */export default { path: '/',  component: Core, indexRoute: {   getComponent(location, cb) {    ...  }, }, childRoutes: [  {   path: 'about',    getComponent(location, cb) {    ...   },  },  {   path: 'users',    getComponent(location, cb) {    ...   },  },  {   path: '*',    getComponent(location, cb) {    ...   },  }, ],};

正常打包

import IndexPage from './views/app.jsx'import AboutPage from './views/about.jsx'export default function({history}) {  return (    <Router history={history}>      <Route path="/" component={IndexPage} />      <Route path="/about" component={AboutPage} />    </Router>  )}

這是一個正常打包的路由寫法, 如果需要分割代碼, 我們需要改造下路由, 借助getComponent和require.ensure

webpack 代碼分割

export default function({history}) {  return (    <Router history={history}>      <Route path="/" getComponent={(location, callback) => {        require.ensure([], function(require) {          callback(null, require('./HomePage.jsx'))        })      }} />      <Route path="/about" getComponent={(location, callback) => {        require.ensure([], function(require) {          callback(null, require('./AboutPage.jsx'))        })      }} />    </Router>  )}

這樣看來代碼有點累, 我們稍微改造下

const home = (location, callback) => { require.ensure([], require => {  callback(null, require('./HomePage.jsx')) }, 'home')}const about = (location, callback) => { require.ensure([], require => {  callback(null, require('./AboutPage.jsx')) }, 'about')}export default function({history}) {  return (    <Router history={history}>      <Route path="/" getComponent={home}></Route>      <Route path="/about" getComponent={about}></Route>    </Router>  )}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 巴南区| 柳河县| 临邑县| 昌吉市| 平潭县| 元朗区| 德保县| 东乌珠穆沁旗| 新平| 瓦房店市| 融水| 闸北区| 鸡西市| 肇庆市| 陕西省| 长武县| 常宁市| 左云县| 高青县| 土默特右旗| 防城港市| 邵东县| 离岛区| 平远县| 鄂伦春自治旗| 惠水县| 稷山县| 舟山市| 福安市| 梅州市| 罗江县| 弋阳县| 大渡口区| 江达县| 嘉善县| 广南县| 西盟| 西盟| 合水县| 大化| 陕西省|