6.webpack 实战优化

# 6.webpack 实战优化

# 通过 splitChunksPlugin 进行代码分割,利用 HTTP 缓存提升性能

// 哪些包需要打入到 vendor 中
// 不要轻易修改,使用 vendor 的 long cache
// 如果需要新增 npm 包,需要修改这里的配置,同时修改 banners/dll/index.vue 中的引用
 npmVendor =
  "vue|svgaplayerweb|dayjs|vue-awesome-swiper|vue-marquee-text-component|axios|qs";
config.optimization.splitChunks({
  ...config.optimization.get("splitChunks"),
  automaticNameDelimiter: "-",
  minChunks: 1,
  cacheGroups: {
    vendors: {
      name: "vendors",
      test: new RegExp(`[\\\\/]node_modules[\\\\/](${npmVendor})[\\\\/]`),
      chunks: "initial",
      priority: 1,
      reuseExistingChunk: true,
      enforce: true,
      // 可能会因为上面的顺序,导致生成的 vendor 文件的 hash 不一致
      // 使用配置的库名生成内容 hash
      // 使用配置的库的版本生成版本 hash,当升级某个库时,版本 hash 会自动修改
      // 使用 contentHash 最保险,但是文件末尾加上 sourceMapURL 之后,相同内容的文件,hash 不一样
      filename:
        NODE_ENV === "production"
          ? "[name].[contenthash:8].dll.js"
          : "[name].dll.js",
    },
  },
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Last Updated: 9/25/2026, 2:08:32 PM