webpack
import() 与 拆包
page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
111
<button class="test">test</button>
<script src="dist/bundle.js"></script>
</body>
</html>
index.js
import bar from "./b";
bar();
window.onload = function () {
document.querySelector(".test").addEventListener("click", () => {
console.log("click");
import("./a.js").then(({ default: _ }) => _());
});
};
webpack.config.js
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
b文件为正常引入,a文件为动态引入。默认最简配置后打包结果:
动态部分被强制拆为单独包。
打开 page.html
只有 page 和 bundle 作为 initial 资源被加载。
点击后加载: