webpack

import() 与 拆包

image.png
page.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. 111
  11. <button class="test">test</button>
  12. <script src="dist/bundle.js"></script>
  13. </body>
  14. </html>

index.js

  1. import bar from "./b";
  2. bar();
  3. window.onload = function () {
  4. document.querySelector(".test").addEventListener("click", () => {
  5. console.log("click");
  6. import("./a.js").then(({ default: _ }) => _());
  7. });
  8. };

webpack.config.js

  1. const path = require('path');
  2. module.exports = {
  3. entry: './index.js',
  4. output: {
  5. path: path.resolve(__dirname, 'dist'),
  6. filename: 'bundle.js'
  7. }
  8. };

b文件为正常引入,a文件为动态引入。默认最简配置后打包结果:
image.png
动态部分被强制拆为单独包。
打开 page.html
image.png
只有 page 和 bundle 作为 initial 资源被加载。
点击后加载:
image.png