webpack 项目优化(一)


一、构建速度优化

  1. 缩小文件处理范围

    module: {
      rules: [{
        test: /\.js$/,
        exclude: /node_modules/, // 排除第三方库
        include: path.resolve(__dirname, 'src'), // 限定处理范围
        use: 'babel-loader'
      }]
    }
    
  2. 利用缓存

    • Webpack 5+ 内置持久化缓存(直接配置):
      cache: { type: 'filesystem' } // 大幅提升二次构建速度
      
    • Babel 缓存
      use: {
        loader: 'babel-loader',
        options: { cacheDirectory: true } // 缓存 Babel 编译结果
      }
      
  3. 多线程/并行处理

    // 安装 thread-loader
    module: {
      rules: [{
        test: /\.js$/,
        use: ['thread-loader', 'babel-loader'] // 多线程编译
      }]
    }
    

二、产物体积优化

  1. 代码分割(Code Splitting)

    optimization: {
      splitChunks: {
        chunks: 'all', // 分离公共代码(如第三方库)
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors'
          }
        }
      }
    }
    
  2. Tree Shaking

    • 确保使用 ES Module 语法(import/export
    • 生产模式自动启用(mode: 'production'
  3. 压缩优化

    const TerserPlugin = require('terser-webpack-plugin');
    const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
    
    optimization: {
      minimize: true,
      minimizer: [
        new TerserPlugin(), // 压缩 JS
        new CssMinimizerPlugin() // 压缩 CSS
      ]
    }
    
  4. 图片资源优化

    // 使用 image-webpack-loader(需安装)
    {
      test: /\.(png|jpg|gif)$/,
      use: [
        'file-loader',
        { loader: 'image-webpack-loader', options: { mozjpeg: { quality: 50 } } }
      ]
    }
    

三、开发体验优化

  1. 热更新(HMR)

    devServer: {
      hot: true, // 启用模块热替换
      compress: true // 启用 gzip 压缩
    }
    
  2. Source Map 选择

    // 开发环境:快速构建
    devtool: 'cheap-module-source-map',
    // 生产环境:安全追踪
    devtool: 'nosources-source-map'
    

四、进阶优化技巧

  1. 动态加载(Lazy Loading)

    // 使用 import() 语法实现按需加载
    const module = await import('./module.js');
    
  2. 外部化依赖(Externals)

    externals: {
      react: 'React', // 通过 CDN 引入 React
      lodash: '_'
    }
    
  3. Scope Hoisting(作用域提升)

    optimization: {
      concatenateModules: true // Webpack 默认开启
    }
    

五、分析工具辅助

  1. 打包体积分析

    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer');
    plugins: [new BundleAnalyzerPlugin()]
    
  2. 构建速度分析

    const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
    module.exports = new SpeedMeasurePlugin().wrap(config);
    

注意事项

  • 按需优化:先用 webpack-bundle-analyzer 分析瓶颈,再针对性处理。
  • 权衡缓存:缓存可能增加磁盘占用,但能显著提升二次构建速度。
  • 版本升级:Webpack 5+ 已内置多项优化,优先升级工具链。

通过结合项目实际情况选择优化手段,可有效提升开发效率和用户体验。

你可能感兴趣的:(webpack,前端,node.js)