当前位置: 首页> 财经> 产业 > vue2 webpack使用optimization.splitChunks分包,实现按需引入,进行首屏加载优化

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

时间:2025/8/23 22:21:13来源:https://blog.csdn.net/qq_41231694/article/details/140180504 浏览次数: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 packagepriority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or apptest: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm},commons: {name: 'chunk-commons',test: resolve('src/components'), // can customize your rulesminChunks: 3, //  minimum common numberpriority: 5,reuseExistingChunk: true}}}}
}

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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: