react-router4 按需加載分析

require.ensure被react-router4x遺棄以后,各種問題接踵而來, 使用了叫做asyncComponent一個加載組建,看了看源碼,他使用了一個函數返回組建的方式,來嵌套了一層,而且返回的還是import加載的形式,感覺很詫異跟直接import有什么卻別?翻了翻es6 API 沒看出所以然。
于是趕緊翻看webpack里的介紹,豁然開朗【import('path/to/module') -> Promise :動態(tài)地加載模塊。調用 import() 之處,被作為分離的模塊起點,意思是,被請求的模塊和它引用的所有子模塊,會分離到一個單獨的 chunk 中?!窟@個就是RR4跟3在結構調整上的區(qū)別了。

//我的路由加載模塊部分
let ViewIndex =  asyncComponent(()=>import( "../view/index/index.js"));
//asyncComponent代碼
import React, { Component } from "react";

export default function asyncComponent(importComponent) {
  class AsyncComponent extends Component {
    constructor(props) {
      super(props);
  
      this.state = {
        component: null
      };
    }

    async componentDidMount() {
      const { default: component } = await importComponent();
      
      this.setState({
        component: component
      });
    }

    render() {
      const C = this.state.component;
        
      return C ? <C {...this.props} /> : null;
    }
  }

  return AsyncComponent;
}

但是問題又來了,chunk名稱以id的形式出現,不容易區(qū)分到底是誰,于是翻看解析源碼,原來是留有復值的地方的, 已經生成好了,還是webpack的問題,于是接著在webpack的import中找。

var ViewIndex = (0, _AsyncComponent2.default)(function () {
  return __webpack_require__.e/* import() */(3).then(__webpack_require__.bind(null, 765));
});
__webpack_require__.e = function requireEnsure(chunkId) {
/******/        var installedChunkData = installedChunks[chunkId];
/******/        if(installedChunkData === 0) {
/******/            return new Promise(function(resolve) { resolve(); });
/******/        }
/******/
/******/        // a Promise means "currently loading".
/******/        if(installedChunkData) {
/******/            return installedChunkData[2];
/******/        }
/******/
/******/        // setup Promise in chunk cache
/******/        var promise = new Promise(function(resolve, reject) {
/******/            installedChunkData = installedChunks[chunkId] = [resolve, reject];
/******/        });
/******/        installedChunkData[2] = promise;
/******/
/******/        // start chunk loading
/******/        var head = document.getElementsByTagName('head')[0];
/******/        var script = document.createElement('script');
/******/        script.type = 'text/javascript';
/******/        script.charset = 'utf-8';
/******/        script.async = true;
/******/        script.timeout = 120000;
/******/
/******/        if (__webpack_require__.nc) {
/******/            script.setAttribute("nonce", __webpack_require__.nc);
/******/        }
/******/        script.src = __webpack_require__.p + "" + ({"1":"index","3":"ViewIndex","4":"ViewInfos"}[chunkId]||chunkId) + "-chunk.js";
/******/        var timeout = setTimeout(onScriptComplete, 120000);
/******/        script.onerror = script.onload = onScriptComplete;
/******/        function onScriptComplete() {
/******/            // avoid mem leaks in IE.
/******/            script.onerror = script.onload = null;
/******/            clearTimeout(timeout);
/******/            var chunk = installedChunks[chunkId];
/******/            if(chunk !== 0) {
/******/                if(chunk) {
/******/                    chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));
/******/                }
/******/                installedChunks[chunkId] = undefined;
/******/            }
/******/        };
/******/        head.appendChild(script);
/******/
/******/        return promise;
}

果然下面有介紹:【import 規(guī)范不允許控制模塊的名稱或其他屬性,因為 "chunks" 只是 webpack 中的一個概念。幸運的是,webpack 中可以通過注釋接收一些特殊的參數,而無須破壞規(guī)定】

import(
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  '你的模塊地址'
);

怎么用如此卑劣的方法處理這么嚴肅的事情,不好理解也不好看,容易被其他壓縮組件給和諧掉,不知道怎么想的但是解決了問題,就此了事,等出現和諧問題后再想其他辦法吧。

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容