主要原因
在项目中,我们发现打包出来的源码比较庞大,并且引用关系十分混乱,具体表现在:
- 引用多个版本的包
 
- 项目中存在很多冗余文件
 
- 项目中引用了无用的包
 
- 多打包入口导致包重复引用
 
分析辅助工具
有一个npm工具包,叫做webpack-bundle-analyzer,安装后可以启动一个打包分析界面。
具体在webpack.config.js中配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
   | const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")   .BundleAnalyzerPlugin; module.exports = {      plugins: [          new BundleAnalyzerPlugin(),                                                                         ], };
  | 
 
执行npm命令时,会自动打开起分析页面,界面类似:

多入口打包交叉引用问题
比如有这样几个文件,均在./src/bundle-test目录下:
a.js
1 2 3 4 5 6 7 8
   | const a = () => {   console.log("isA");   console.log(c()); }; import c from "./c"; const vue = require("vue");
  export default a;
  | 
 
b.js
1 2 3 4 5 6 7 8 9
   | const b = () => {   console.log("isB");   console.log(c()); };
  import c from "./c"; const vue = require("vue");
  export default b;
  | 
 
c.js
1 2 3 4 5
   | const c = () => {   console.log("isC"); };
  export default c;
  | 
 
index.js
1 2 3 4 5 6 7 8 9
   | import A from "./a.js"; import B from "./b.js";
  const test = () => {   console.log("isI");   A();   B(); }; test();
   | 
 
分别按入口打包:
1 2 3 4 5 6 7 8 9
   | entry: {     index: "./src/bundle-test/index.js",     a: "./src/bundle-test/a.js",   },    output: {     filename: "[name].js",      libraryTarget: "umd",      path: path.resolve(__dirname, "lib"),    },
  | 
 
优化前:

我们使用webpack的splitChunks规则,使得公共模块抽离出来
在webpack.config.js下配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | optimization: {     minimize: false,          splitChunks: {       minSize: 30,        cacheGroups: {         default: {           name: "common",           chunks: "initial",           minChunks: 2,            priority: 1,          },       },     },   },
  | 
 
优化后:

可以看到,优化后打包大小几乎减小了一半。