webpack常见优化方法

发布于:2025-02-10 ⋅ 阅读:(35) ⋅ 点赞:(0)

1. Webpack 的主要作用

1. 模块打包

  • 将各种资源(JS、CSS、图片等)视为模块
  • 把所有模块打包成少量的静态资源文件
  • 代码转换
  • 将 ES6+ 转换为 ES5
  • 将 SCSS/LESS 转换为 CSS
  • 将 TypeScript 转换为 JavaScript
  • 文件优化
  • 压缩代码
  • 合并文件
  • 代码分割

2. 减小打包体积的方法

  • 代码分割 (Code Splitting)
  • // webpack.config.js
    module.exports = {
      optimization: {
        splitChunks: {
          chunks: 'all',
          minSize: 20000,
          minChunks: 1,
          maxAsyncRequests: 30,
          maxInitialRequests: 30,
          cacheGroups: {
            vendors: {
              test: /[\\/]node_modules[\\/]/,
              priority: -10
            },
            default: {
              minChunks: 2,
              priority: -20,
              reuseExistingChunk: true
            }
          }
        }
      }
    }
  • 压缩代码

    // webpack.config.js
    const TerserPlugin = require('terser-webpack-plugin');
    
    module.exports = {
      optimization: {
        minimize: true,
        minimizer: [new TerserPlugin()],
      }
    }
  • Tree Shaking(移除未使用的代码)
    // package.json
    {
      "sideEffects": false
    }
    
    // webpack.config.js
    module.exports = {
      mode: 'production',  // 启用 tree shaking
      optimization: {
        usedExports: true
      }
    }
  • 使用动态导入

    // 代码中使用动态导入

    const Component = () => import('./Component.vue')
  • 压缩图片
    // webpack.config.js
    module.exports = {
      module: {
        rules: [
          {
            test: /\.(png|jpg|gif)$/i,
            use: [
              {
                loader: 'image-webpack-loader',
                options: {
                  mozjpeg: {
                    progressive: true,
                    quality: 65
                  }
                }
              }
            ]
          }
        ]
      }
    }

6. 使用 gzip 压缩

// webpack.config.js
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  plugins: [
    new CompressionPlugin({
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    })
  ]
}

3. 其他优化建议

  • 分析打包大小
    # 使用 webpack-bundle-analyzer 分析包大小
    npm install --save-dev webpack-bundle-analyzer

2. 优化第三方库的引入

// 按需引入

import { Button } from 'element-ui'  // 而不是 import ElementUI from 'element-ui'

3. 配置 externals

// webpack.config.js

module.exports = {

  externals: {

    'vue': 'Vue',

    'vue-router': 'VueRouter',

    'vuex': 'Vuex'

  }

}
  • 使用 CDN
    <!-- index.html -->
    
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>

4. 实际效果监控

  • 使用 webpack-bundle-analyzer 查看打包结果
    // webpack.config.js
    
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
    
    module.exports = {
    
      plugins: [
    
        new BundleAnalyzerPlugin()
    
      ]
    
    }

网站公告

今日签到

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