Vue 打包 chunk-vendors.js 文件过大导致页面加载缓慢解决方案

2,007 阅读1分钟

chunk-vendors.js 简介

  • 顾名思义,chunk-vendors.js 是捆绑所有不是自己的模块,而是来自其他方的模块的捆绑包,它们称为第三方模块或供应商模块。

  • 通常,它意味着(仅和)来自项目 /node_modules 目录的所有模块,会将所有 /node_modules 中的第三方包打包到 chunk-vendors.js 中。

  • 将所有的第三方包集中到一个文件,自然也会出现文件过大的问题。

解决方案

方案一 compression-webpack-plugin 插件解决方案

    // 引入compression-webpack-plugin
    const CompressionPlugin = require('compression-webpack-plugin')
    
    // 当前环境是vue.config.js 文件下的配置
    chainWebpack: (config) => {
        config.plugin('compressionPlugin').use(new CompressionPlugin({
            test: /\.(js|css|less)$/, // 匹配文件名
            threshold: 1024, // 对超过10k的数据压缩
            deleteOriginalAssets: false, // 不删除源文件
            minRatio: 0.3, // 压缩比
          }))
    }

方案二 使用webpack optimization 进行对大文件分包打包

    // 当前环境是vue.config.js 文件下的配置
    configureWebpack: config => {
        return {
        // 开启分离 js
        optimization: {
          runtimeChunk: 'single',
          splitChunks: {
            chunks: 'all',
            maxInitialRequests: Infinity,
            minSize: 20000,
            cacheGroups: {
              vendor: {
                test: /[\\/]node_modules[\\/]/,
                name(module) {
                  // get the name. E.g. node_modules/packageName/not/this/part.js
                  // or node_modules/packageName
                  const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                  // npm package names are URL-safe, but some servers don't like @ symbols
                  return `npm.${packageName.replace('@', '')}`
                }
              }
            }
          }
        }
      }
    }