一个 H5 项目,用户基本都在微信里打开。首包 4.2M,4G 网络下白屏 8 秒。老板说"能不能快点",于是开始了这场拉锯。
uni-app 打包后看 dist/build/h5/static/js/:
4.2M chunk-vendors.js
380K index.js
220K pages-index-index.js
一个文件 4.2M,gzip 后 1.1M。问题很明显。
// vue.config.js
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vue: { name: 'vue', test: /[\\/]node_modules[\\/](vue|vue-router|vuex)[\\/]/ },
ui: { name: 'ui', test: /[\\/]node_modules[\\/](uview|vant)[\\/]/ }
}
}
}
}
拆完之后首屏只需要 vue 那个 chunk,其他按需加载。首包降到 2.9M。
静态图 1.4M,全是 PNG。转 webp:
for f in static/images/*.png; do
cwebp -q 82 "$f" -o "${f%.png}.webp"
done
体积从 1.4M 降到 480K。兼容性上微信内核早就支持 webp 了,只有极老的安卓 4.x 不行,那部分用户本来也打不开这个项目。
原先 import uView from 'uview-ui' 全量引入。改成用哪个引哪个,或者配 easycom 自动按需。
省了 380K。
生产环境不需要。productionSourceMap: false。省 600K。
// pages.json
"subPackages": [
{ "root": "pages/merchant", "pages": [...] },
{ "root": "pages/admin", "pages": [...] }
]
商家端和后台两套页面,普通用户根本用不到,全扔分包里。首包又少了 400K。
| 首包 | 4.2M → 2.1M |
| gzip 后 | 1.1M → 520K |
| 4G 首屏 | 8s → 2.8s |
(表格样式没写,将就看。)
能。路由懒加载、字体子集化、把 moment 换成 dayjs(省 200K)、去掉没用的 polyfill。但边际收益越来越小,2.1M 已经能接受,就停了。
优化这事有终点。别为了 100K 折腾三天。