vue2 webpack使用optimization.splitChunks分包,实现按需引入,进行首屏加载优化

发布于:2024-07-07 ⋅ 阅读:(49) ⋅ 点赞:(0)

optimization.splitChunks的具体功能和配置信息可以去网上自行查阅。

这边简单讲一下他的使用场景、作用、如何使用:

1、没用使用splitChunks进行分包之前,所有模块都揉在一个文件里,那么当这个文件足够大、网速又一般的时候,首屏加载就会很慢。如下图,这三块会在首次进入项目的时候会一起加载:

在这里插入图片描述

2、这时,我们使用splitChunks进行分包,在vue.config.js进行配置,代码如下:

module.exports = {
  configureWebpack: {
    optimization: {
       splitChunks: {
	   chunks: 'all',
	   cacheGroups: {
	       libs: {
	         name: 'chunk-libs',
	         test: /[\\/]node_modules[\\/]/,
	         priority: 10,
	         chunks: 'initial' // only package third parties that are initially dependent
	       },
	       elementUI: {
	         name: 'chunk-elementUI', // split elementUI into a single package
	         priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
	         test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
	       },
	       commons: {
	         name: 'chunk-commons',
	         test: resolve('src/components'), // can customize your rules
	         minChunks: 3, //  minimum common number
	         priority: 5,
	         reuseExistingChunk: true
	       }
	   }
     }
   }
}

cacheGroupssplitChunks里面最核心的配置,splitChunks就是根据cacheGroups去拆分模块的。
配置完成以后,在进行打包,模块就会进行分包。如下图:
在这里插入图片描述
这时候,当你进入某个页面,用到某个模块的时候,对应的模块包才会进行加载,实现按需加载,这样能大幅优化首屏加载缓慢的问题


网站公告

今日签到

点亮在社区的每一天
去签到