ijiwei-activity 活动页项目优化
打包结果分析
首先, 借助 webpack-bundle-analyzer
对结果进行分析, 然后找哪里出了问题。
分析
1. 图片被打包进去了
可以看到,打包把一部分图片页打包进去了,这个是 url-loader
的特性,因此我们可以尝试调整 url-loader 的 limit
。 我们最终设置了 limit 是 0 。
2. 使用 CDN
可以看到 jQuery 和 Swiper 也被打包了进去,可以用使用 CDN 资源。这里需要配置 external
。
由于 Swiper 用了多种使用方式 CDN 和 esm 模式,并且版本较老,怕影响代码,因此没有对它拆分。
3. 图片拆分
如果我们的 limit 设置的不是 0 我们还可以通过拆包把图片这部分拆分出来,这里需要设置 splitChunks
// ...
splitChunks: {
cacheGroups: {
default: false,
common: {
name: 'common',
chunks: 'all',
priority: 10,
minChunks: 2,
minSize: 0,
maxInitialRequests: 5,
reuseExistingChunk: true,
},
vendors: {
test: /[\\/]node_modules[\\/]/,
chunks: 'all',
priority: 20,
minSize: 0,
minChunks: 1,
enforce: true,
reuseExistingChunk: true,
},
imgs: { // 将 图片拆分 出来
name: 'imgs',
test: /\.(svg|jpe?g|png)$/,
chunks: 'all',
enforce: true,
priority: 15 // 优先级要高于 common , 不然应该拆不出来
}
},
}
以上三步完成后,可以看到 main.hash.js
Gzip 压缩后的结果已经从 290KB 降到 60KB
4. 配合 lighthoust 分析
使用浏览器带的 lighthouse,对页面进行性能分析。
点击
view origin trice
查看详情。
可以在上图的最下面看到,main.hash.js 的网络传输要 5.88s,这里不确定传输的时间包括了哪些过程,以及造成的原因,可能是网速的原因把。
我们的活动页面是很多活动糅杂在一起的, 访问一个活动的时候其他活动页面资源完全不需要加载或者延后加载。我们可以使用 prefetch
做一个预读取,再使用 preload
对主要页面进行预加载。
const routes = [
{
path: '/',
redirect: '20211118/index',
component: Index,
children: [
{
path: '20211118/index',
name: 'Car',
component: ()=>import(/* webpackPrefetch:true */'../pages/Car/2021/Index')
},
{
path: 'car/2022',
name: 'Car2022',
component: ()=>import(/* webpackPreload:true */'../pages/Car/2022/Index')
},
{
path: 'car/2022/hlist',
name: 'Car2022hlist',
component: ()=>import(/* webpackPrefetch:true */'../pages/Car/2022/Hlist')
},
// ...
}