webpack常见优化方法

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
                  }
                }
              }
            ]
          }
        ]
      }
    }
  1. 使用 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
  1. 优化第三方库的引入

    // 按需引入

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

  2. 配置 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()
    
      ]
    
    }
相关推荐
DianSan_ERP8 分钟前
多平台订单自动下载与回传的技术实现:从消息推送到状态闭环引言
java·linux·服务器·前端·网络·架构·自动化
恋猫de小郭8 分钟前
Shopify 回应为什么从 RN 回到原生,为什么不用 KMP ?
android·前端·flutter
小蜗 strong41 分钟前
和电脑猜拳(随机程序应用)
服务器·前端·python
下家2 小时前
为了脱离前端鄙视链,于是自己写个框架 - React 党看完沉默了
前端·前端框架
zhiyouTech2 小时前
从“被看见“到“被信任“:关于信源评级机制的一点观察
大数据·前端·人工智能
Hashan2 小时前
Vibe Coding 下前后端怎么对接接口?后端不给力的兜底方案
前端·后端·vibecoding
你挚爱的强哥3 小时前
【sgKeyboard】自定义组件:虚拟键盘
前端·javascript·计算机外设
锅里游的鱼吖3 小时前
echarts自定义折线图
前端·javascript·数据库
hunteritself3 小时前
卷卷卷!GPT-6 Sol、Luna 正式发布,OpenAI 开始卷价格了
大数据·前端·人工智能·深度学习·transformer
何何____4 小时前
Vue 全局事件总线详解
前端·javascript·vue.js