运行时单一实例选项
运行时单一实例
我们把webpack.config.js中配置了一个优化选项,其中配置runtimeChunk设置为single。然后我们修改了一下index和other-bundle.js文件。
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "development",
entry: {
index: {
import: "./src/index.js",
dependOn: "shared",
},
"other-bundle": {
import: "./src/other-bundle.js",
dependOn: "shared",
},
shared: "lodash",
},
+ optimization: {
+ runtimeChunk: "single",
+ },
output: {
filename: "[name].[contenthash].bundle.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "资源输出",
filename: "webpack.html",
}),
],
};
index.js
import _ from "lodash";
import count from "./count.js";
count.count++;
console.log("index",count.count);
other-bundle.js
import _ from "lodash";
import count from "./count.js";
count.count++;
console.log("other",count.count);
count.js
export default {
count: 0,
};
在index.js和other-bundle中都引入了count.js,在count.js中是暴露出了一个对象。在我们上面的webpack.config.js,配置了optimization.runtimeChunk='single。
打包后,webpack.html中的控制台输出内容如下,对于2个模块内部,看得出来count对象只实例化了一次。
index 1
other 2
通过webpack运行时,可以了解到,实际上我们让这个共享的对象满足最终打包生成的runtime在同一个作用域的时候就可以实现如上的输出结果。
那么相反来看,如果我们不对lodash进行提取,让这个唯一一个外部引入的共享模块存在于这2个js打包文件中,然后设置optimization.runtimeChunk=true(multiple),那么最后会对index.js和other-bundle.js都生成一个runtime的文件,这个时候最后控制台中输出的是。
index 1
other 1