Webpack DLLPlugin 问题处理记录

最近在给企业版页面引入 gitee-vendor-dll 包中的 echarts 库后出了点问题,部分未使用 echarts 的页面会报错未找到 echarts 依赖库,初步推测问题原因出在 DllPlugin 和 DllReferencePlugin 上。

webpack 文档上对 DllReferencePlugin 插件的工作模式介绍是这样的:

dll 中的内容被映射到了当前目录下。如果一个被 require 的文件符合 dll 中的某个文件(解析之后),那么这个dll中的这个文件就会被使用。

在使用 DllReferencePlugin 插件时,自然会习惯性认为它只会给主动引入了 echarts 的模块添加 echarts 依赖,然而从实际效果来看,它会给 entry 配置中的所有入口文件加上 echarts 依赖,假设 DllReferencePlugin 确实能够正常工作,那么问题原因可能在于输出的 dll 包含了除 echarts 外全局共用的模块。

先看看 webpack 为 echarts 输出的 manifest.json 内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"name": "echarts_lib",
"content": {
"../node_modules/echarts/dist/echarts.common.js": {
"id": "./node_modules/echarts/dist/echarts.common.js",
"buildMeta": {
"providedExports": true
}
},
"../node_modules/webpack/buildin/global.js": {
"id": "./node_modules/webpack/buildin/global.js",
"buildMeta": {
"providedExports": true
}
}
}
}

内容很简单,可以看到多了个 webpack/buildin/global.js 文件,经测试,删掉这项记录可以解决问题,那么该如何让 manifest.json 不包含这个文件?有两个选择:

  1. 向 webpack 反馈问题,让官方给出标准解决方案
  2. 手写 JavaScript 代码,在 webpack 执行完后更新 manifest.json 文件

stats-webpack-plugin 插件的用法

stats-webpack-plugin 插件能够生成资源清单文件,被用于 Gitee 的一些前端项目中,这个清单文件有两个用途:

  1. 让服务器端能够根据 Webpack 配置的入口名称找到资源文件路径
  2. 在线上环境出现问题需要回滚时,可以通过回退清单文件来快速将前端资源切换回上个版本,无需花时间重新打包构建前端资源

由于最近在处理资源清单文件合并问题时折腾了 stats-webpack-plugin 插件,所以顺便记录一些关于这个插件的用法。

基本用法:

1
2
3
4
5
6
7
8
9
10
const StatsPlugin = require('stats-webpack-plugin')

module.exports = {
plugins: [
new StatsPlugin('stats.json', {
chunkModules: true,
exclude: [/node_modules[\\\/]react/]
})
]
};

使用 cache 参数让多个 StatsPlugin() 插件实例将构建统计信息写入到同一 stats.json 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const options = {
chunkModules: true,
exclude: [/node_modules[\\/]/]
}

const cache = {}

module.exports = [
{
plugins: [
new StatsPlugin('stats.json', options, cache)
]
},
{
plugins: [
new StatsPlugin('stats.json', options, cache)
]
}
]

gitee-vendor-dll 项目的 Webpack 配置是一个数组,按照原有的配置,Webpack 输出的 manifest.json 只会包含第一个配置的资源信息,正好之前在看 stats-webpack-plugin 插件的测试程序时发现了 cache 参数,所以用它解决了问题。

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×