简单的通过 require.ensure代码分割
a
和b
通过CommonJS引入c
通过webpack的require.ensure
引入.- webpack将c打包打包并且按需加载
b
和d
在require.ensure
的回调函数通过CommonJS引入- webpack 检测到b和d实在回调函数里,也会被按需加载
- b已经在上边引入过一次,webpack会优化,只留一个b模块
example.js
var a = require("a");
var b = require("b");
require.ensure(["c"], function(require) {
require("b").xyz();
var d = require("d");
});
webpack.config.js
```javascript module.exports = { optimization: { chunkIds: “deterministic” // To keep filename consistent between different modes (for example building only) } };
<a name="QFQzn"></a>
# dist/796.js
```javascript
(self["webpackChunk"] = self["webpackChunk"] || []).push([[796],{
/***/ "./node_modules/c.js":
/*!***************************!*\
!*** ./node_modules/c.js ***!
\***************************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: */
/***/ (() => {
// module c
/***/ }),
/***/ "./node_modules/d.js":
/*!***************************!*\
!*** ./node_modules/d.js ***!
\***************************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: */
/***/ (() => {
// module d
/***/ })
}]);
dist/main.js
/...省略 ... /
var a = __webpack_require__(/*! a */ "./node_modules/a.js");
var b = __webpack_require__(/*! b */ "./node_modules/b.js");
__webpack_require__.e(/*! require.ensure */ 796).then((function(require) {
__webpack_require__(/*! b */ "./node_modules/b.js").xyz();
var d = __webpack_require__(/*! d */ "./node_modules/d.js");
}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
/...省略 ... /