跳到主要内容

重复模块引入处理

重复引入一个模块,多入口打包

现在修改一下文件结构

...
|--- src
|--- index.js
- |--- print.js
+ |--- other-bundle.js
...

在index.js引入过lodash,现在在other-bundle.js中同样引入lodash,然后再index.js中引入other-bundle.js

other-bundle.js

import _ from "lodash";

console.log("other bundle");

index.js

import _ from "lodash";
import "./other-bundle";

function component() {
const element = document.createElement("div");

element.innerHTML = _.join(["Hello", "webpack"], " ");

return element;
}

document.body.appendChild(component());

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
mode: "development",
entry: {
index: "./src/index.js",
- print: "./src/print.js"
+ "other-bundle": "/src/other-bundle.js",
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "资源输出",
filename: "webpack.html",
}),
],
};

现在打包之后,发现打包生成的index.bunlde.lsother-bundle.bundle.js中都有下面的一段内容。很显然,现在在这2个bundle中都引入了lodash,造成了重复引入。


/***/ "./node_modules/lodash/lodash.js":
/*!***************************************!*\
!*** ./node_modules/lodash/lodash.js ***!
\***************************************/

排除重复引入

入口依赖

入口依赖,是通过在webpack.config.js中指明入口文件所依赖的包,来进行包的引入。

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
mode: "development",
entry: {
- index: "/src/index.js",
- "other-bundle": "/src/other-bundle.js",
+ index: {
+ import: "./src/index.js",
+ dependOn: "shared",
+ }
+ "other-bundle": {
+ import: "./src/other-bundle.js",
+ dependOn: "shared",
+ }
+ shared: "lodash",
},

output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "资源输出",
filename: "webpack.html",
}),
],
};

这里通过对一个入口配置了dependOn属性,dependOn依赖的是另外一个配置的入口文件(不带路径就是从node_modules下面寻找)。最后生成的前2个入口文件中,就没有引入lodash的代码,而是都引入的是shared入口文件输出的目标文件。如果不设置dependOn,那么index和other-bundle的输出文件中,都会包含lodash的依赖代码,造成臃肿。

动态导入

插件SplitChunks