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()
    
      ]
    
    }
相关推荐
brzhang4 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
止观止4 小时前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
goms4 小时前
前端项目集成lint-staged
前端·vue·lint-staged
谢尔登5 小时前
【React Natve】NetworkError 和 TouchableOpacity 组件
前端·react.js·前端框架
Lin Hsüeh-ch'in5 小时前
如何彻底禁用 Chrome 自动更新
前端·chrome
augenstern4167 小时前
HTML面试题
前端·html
张可7 小时前
一个KMP/CMP项目的组织结构和集成方式
android·前端·kotlin
G等你下课7 小时前
React 路由懒加载入门:提升首屏性能的第一步
前端·react.js·前端框架
蓝婷儿8 小时前
每天一个前端小知识 Day 27 - WebGL / WebGPU 数据可视化引擎设计与实践
前端·信息可视化·webgl
然我8 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法