在使用 webpack 构建的 vue 应用中,我们常面临一个重要的性能问题:
打包构建的单个静态文件太大,导致加载请求的时间长,页面加载速度慢。
我们有两个解决方向:
1. 构建分包
即将我们引入的一些第三方向和资源进行分包处理,构建成多个小包,避免一个文件过大,可以随着页面变化的请求而变化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
   | module.exports = defineConfig({     configureWebpack: {         optimization: {             runtimeChunk: "single",             splitChunks: {                 chunks: "all",                 maxInitialRequests: 10,                                  minSize: 1024 * 1 * 1000,                                  maxSize: 1024 * 2 * 1000,                 cacheGroups: {                     vendors: {                         test: /[\\/]node_modules[\\/]/,                         priority: -10,                         name(module) {                             const matchResult = module.context.match(                                 /[\\/]node_modules[\\/](.*?)([\\/]|$)/                             );                             const packageName = matchResult                                 ? matchResult[1]                                 : "";                             return `npm.${packageName.replace("@", "")}`;                         },                     },                 },             },         },     },          transpileDependencies: [/node_modules[/\\\\]/], });
  | 
 
2. 使用 GZip 压缩
在我们的 webpack 配置中,可以这样配置
1 2 3 4 5 6 7 8 9 10 11 12 13
   | const CompressionPlugin = require("compression-webpack-plugin"); module.exports = defineConfig({     plugins: [         process.env.NODE_ENV === "production"             ? new CompressionPlugin({                   test: /\.(js|css)?$/i,                   algorithm: "gzip",                   minRatio: 1,                   deleteOriginalAssets: true,               })             : "",     ], });
  | 
 
上面我们使用了"compression-webpack-plugin": "^10.0.0",插件来完成 gzip 的压缩
在使用 nginx 的服务端环境,还需要配置进行支持:
1 2 3
   | gzip on; gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css; gzip_static on;
   | 
 
这样,就可以提大地提高访问加载速度。
      
     
    
      
  
  
    
      
      
        
        致力于网站建设与Web开发。喜欢新事物,关注前后端动态,对新的技术有追求, 做一个优秀的web全栈工程师。