今天操作webpack时报出几个错误,从提示上可以看出是因为webpack打包文件太大,导致的警告错误,可以手动设置打包文件的大小限制。
错误内容如下:
WARNING
asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
static/8c953eff12.jpg (1.23 MiB)
WARNING
entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
main (252 KiB)
css/app.min.css
js/app.js
“asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance.”意思是“资源大小限制:以下资源超出建议大小限制(244KiB)。这可能会影响Web性能”。
“entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.”意思是:“入口点大小限制:以下入口点组合资源超出建议大小限制(244KiB)。这可能会影响Web性能”。
一、定位问题
以上通过对错误的翻译,显而易见,是资源超出了默认限制,所以我们来看下webpack文档,即可找到对应答案,地址如下:
Performance | webpack 中文文档 | webpack中文文档 | webpack中文网
在webpack文档中,有个performance(性能)选项,展开后就能看到两个参数:maxAssetSize和maxEntrypointSize。如下图:
- maxAssetSize:资源(asset)是从 webpack 生成的任何文件。此选项根据单个资源体积(单位: bytes),控制 webpack 何时生成性能提示。
- maxEntrypointSize:入口起点表示针对指定的入口,对于所有资源,要充分利用初始加载时(initial load time)期间。此选项根据入口起点的最大体积,控制 webpack 何时生成性能提示。
二、手动设置大小
所以,我们在webpack.config.js中,添加相应参数即可,代码如下:
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/app.js',
path: resolve(__dirname, 'build')
},
module: {
rules: [
// ...
]
},
plugins: [
// ...
],
mode: 'production',
performance: {
maxEntrypointSize: 50000000,
maxAssetSize: 30000000,
},
devServer: {
static: resolve(__dirname, 'build'),
port: 3000,
compress: true,
open: true,
hot: true,
}
}
此时重新运行项目,则错误没有了。
三、打开/关闭提示
hits值为:warning、error、false(boolean),打开/关闭提示。此外,当找到提示时,告诉 webpack 抛出一个错误或警告。此属性默认设置为 "warning"。
所以,也可以关闭这个开关,代码如下:
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/app.js',
path: resolve(__dirname, 'build')
},
module: {
rules: [
// ...
]
},
plugins: [
// ...
],
mode: 'production',
performance: {
hints: false
},
devServer: {
static: resolve(__dirname, 'build'),
port: 3000,
compress: true,
open: true,
hot: true,
}
}
此时,再次运行项目,错误也没有了。