简单的通过 require.ensure代码分割

  • ab 通过CommonJS引入
  • c 通过webpack的 require.ensure 引入.
    • webpack将c打包打包并且按需加载
  • bdrequire.ensure 的回调函数通过CommonJS引入
    • webpack 检测到b和d实在回调函数里,也会被按需加载
    • b已经在上边引入过一次,webpack会优化,只留一个b模块

      example.js

      1. var a = require("a");
      2. var b = require("b");
      3. require.ensure(["c"], function(require) {
      4. require("b").xyz();
      5. var d = require("d");
      6. });

      webpack.config.js

      ```javascript module.exports = { optimization: { chunkIds: “deterministic” // To keep filename consistent between different modes (for example building only) } };
  1. <a name="QFQzn"></a>
  2. # dist/796.js
  3. ```javascript
  4. (self["webpackChunk"] = self["webpackChunk"] || []).push([[796],{
  5. /***/ "./node_modules/c.js":
  6. /*!***************************!*\
  7. !*** ./node_modules/c.js ***!
  8. \***************************/
  9. /*! unknown exports (runtime-defined) */
  10. /*! runtime requirements: */
  11. /***/ (() => {
  12. // module c
  13. /***/ }),
  14. /***/ "./node_modules/d.js":
  15. /*!***************************!*\
  16. !*** ./node_modules/d.js ***!
  17. \***************************/
  18. /*! unknown exports (runtime-defined) */
  19. /*! runtime requirements: */
  20. /***/ (() => {
  21. // module d
  22. /***/ })
  23. }]);

dist/main.js

  1. /...省略 ... /
  2. var a = __webpack_require__(/*! a */ "./node_modules/a.js");
  3. var b = __webpack_require__(/*! b */ "./node_modules/b.js");
  4. __webpack_require__.e(/*! require.ensure */ 796).then((function(require) {
  5. __webpack_require__(/*! b */ "./node_modules/b.js").xyz();
  6. var d = __webpack_require__(/*! d */ "./node_modules/d.js");
  7. }).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
  8. /...省略 ... /