单个entry的深层次依赖代码分割

  • pageApageB 是异步加载的
  • pageCpageA 都依赖 reusableComponent
  • pageB 异步加载 PageC

打包后的文件:

  • output.js 是 entry chunk 包括了
    • 模块系统
    • chunk 加载逻辑
    • 入口 example.js
  • 0.output.js
    • reusableComponent
  • 1.output.js
    • module pageB
  • 2.output.js
    • module pageA
  • 3.output.js
    • module pageC

webpack.config.js

  1. "use strict";
  2. const path = require("path");
  3. module.exports = {
  4. // mode: "development || "production",
  5. entry: {
  6. main: ["./example.js"]
  7. },
  8. optimization: {
  9. splitChunks: {
  10. minSize: 0 // This example is too small, in practice you can use the defaults
  11. },
  12. chunkIds: "deterministic" // To keep filename consistent between different modes (for example building only)
  13. },
  14. output: {
  15. path: path.resolve(__dirname, "dist"),
  16. filename: "output.js"
  17. }
  18. };

example.js

  1. var main = function() {
  2. console.log("Main class");
  3. require.ensure([], () => {
  4. const page = require("./pageA");
  5. page();
  6. });
  7. require.ensure([], () => {
  8. const page = require("./pageB");
  9. page();
  10. });
  11. };
  12. main();

pageA.js

  1. var reusableComponent = require("./reusableComponent");
  2. module.exports = function() {
  3. console.log("Page A");
  4. reusableComponent();
  5. };

pageB.js

  1. module.exports = function() {
  2. console.log("Page B");
  3. require.ensure([], ()=>{
  4. const page = require("./pageC");
  5. page();
  6. });
  7. };

pageC.js

  1. var reusableComponent = require("./reusableComponent");
  2. module.exports = function() {
  3. console.log("Page C");
  4. reusableComponent();
  5. };