欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Webpack打包速度優(yōu)化方案匯總

 更新時(shí)間:2025年04月14日 09:25:09   作者:北辰alk  
Webpack 打包速度優(yōu)化是提升開發(fā)效率和構(gòu)建效率的關(guān)鍵,以下是系統(tǒng)化的優(yōu)化方案,從基礎(chǔ)配置到高級(jí)技巧全面覆蓋,并通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下

一、基礎(chǔ)配置優(yōu)化

1.1 區(qū)分開發(fā)與生產(chǎn)環(huán)境

// webpack.config.js
module.exports = (env, argv) => {
  const isProduction = argv.mode === 'production';
  
  return {
    mode: isProduction ? 'production' : 'development',
    devtool: isProduction ? 'source-map' : 'eval-cheap-module-source-map',
    // 其他配置...
  };
};

優(yōu)化點(diǎn)

  • 開發(fā)環(huán)境使用更快的 sourcemap 生成方式
  • 生產(chǎn)環(huán)境啟用完整優(yōu)化但保留 sourcemap

1.2 減少解析范圍

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: path.resolve(__dirname, 'src'),
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    extensions: ['.js', '.jsx'] // 減少擴(kuò)展名嘗試
  }
};

二、Loader 優(yōu)化策略

2.1 限制 loader 應(yīng)用范圍

{
  test: /\.js$/,
  exclude: /node_modules/,
  include: path.resolve(__dirname, 'src'),
  use: ['babel-loader?cacheDirectory']
}

2.2 啟用 loader 緩存

use: [
  {
    loader: 'babel-loader',
    options: {
      cacheDirectory: true // 默認(rèn)緩存目錄 node_modules/.cache/babel-loader
    }
  }
]

2.3 減少 loader 數(shù)量

// 避免不必要的 loader 調(diào)用
{
  test: /\.(jpe?g|png|gif|svg)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 8192 // 小于8KB轉(zhuǎn)為base64
      }
    }
    // 移除不必要的 image-webpack-loader 開發(fā)環(huán)境
  ]
}

三、插件優(yōu)化方案

3.1 選擇性使用插件

const plugins = [
  new webpack.DefinePlugin({/*...*/}),
  isProduction && new MiniCssExtractPlugin()
].filter(Boolean);

3.2 禁用開發(fā)無用插件

plugins: [
  !isDevelopment && new CompressionPlugin(),
  !isDevelopment && new BundleAnalyzerPlugin()
].filter(Boolean)

3.3 使用 HardSourceWebpackPlugin

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

module.exports = {
  plugins: [
    new HardSourceWebpackPlugin()
  ]
};

效果:二次構(gòu)建速度提升60%-80%

四、模塊解析優(yōu)化

4.1 縮小模塊搜索范圍

resolve: {
  alias: {
    '@': path.resolve(__dirname, 'src'),
    react: path.resolve(__dirname, './node_modules/react')
  },
  symlinks: false // 防止npm link導(dǎo)致的重復(fù)解析
}

4.2 使用 module.noParse

module: {
  noParse: /jquery|lodash/ // 忽略未模塊化的庫
}

五、多進(jìn)程并行處理

5.1 thread-loader

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: 'thread-loader',
            options: {
              workers: 2,
              workerParallelJobs: 50,
              poolTimeout: 2000
            }
          },
          'babel-loader'
        ]
      }
    ]
  }
};

5.2 parallel-webpack

// 安裝后直接運(yùn)行
parallel-webpack --config=webpack.config.js

5.3 TerserPlugin 多進(jìn)程

optimization: {
  minimizer: [
    new TerserPlugin({
      parallel: require('os').cpus().length - 1
    })
  ]
}

六、開發(fā)環(huán)境特化優(yōu)化

6.1 禁用生產(chǎn)環(huán)境優(yōu)化

optimization: {
  removeAvailableModules: false,
  removeEmptyChunks: false,
  splitChunks: false,
  minimize: false
}

6.2 使用 cache-loader

{
  test: /\.(js|jsx)$/,
  use: [
    'cache-loader',
    'babel-loader'
  ],
  include: path.resolve('src')
}

6.3 增量編譯

watchOptions: {
  aggregateTimeout: 500, // 防抖延遲
  ignored: /node_modules/ // 忽略目錄
}

七、DLL 預(yù)編譯技術(shù)

7.1 創(chuàng)建 DLL 配置

// webpack.dll.config.js
module.exports = {
  entry: {
    vendor: ['react', 'react-dom', 'lodash']
  },
  output: {
    filename: '[name].dll.js',
    path: path.resolve(__dirname, 'dll'),
    library: '[name]_[hash]'
  },
  plugins: [
    new webpack.DllPlugin({
      name: '[name]_[hash]',
      path: path.join(__dirname, 'dll', '[name]-manifest.json')
    })
  ]
};

7.2 主配置引用 DLL

// webpack.config.js
plugins: [
  new webpack.DllReferencePlugin({
    manifest: require('./dll/vendor-manifest.json')
  })
]

八、高級(jí)優(yōu)化技巧

8.1 使用 SWC 替代 Babel

module: {
  rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: {
        loader: 'swc-loader',
        options: {
          jsc: {
            parser: {
              syntax: 'ecmascript',
              jsx: true
            }
          }
        }
      }
    }
  ]
}

速度對(duì)比:SWC 比 Babel 快 20 倍以上

8.2 使用 esbuild-loader

const { ESBuildMinifyPlugin } = require('esbuild-loader');

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'esbuild-loader',
        options: {
          target: 'es2015'
        }
      }
    ]
  },
  optimization: {
    minimizer: [
      new ESBuildMinifyPlugin({
        target: 'es2015'
      })
    ]
  }
};

8.3 模塊聯(lián)邦共享

// 共享依賴避免重復(fù)打包
new ModuleFederationPlugin({
  name: 'app1',
  shared: {
    react: { singleton: true },
    'react-dom': { singleton: true }
  }
})

九、構(gòu)建分析工具

9.1 速度分析

const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  // 原webpack配置
});

9.2 構(gòu)建耗時(shí)分析

class BuildTimePlugin {
  apply(compiler) {
    let startTime;
    
    compiler.hooks.beforeRun.tap('BuildTime', () => {
      startTime = Date.now();
    });
    
    compiler.hooks.done.tap('BuildTime', stats => {
      console.log(`構(gòu)建耗時(shí): ${(Date.now() - startTime) / 1000}s`);
    });
  }
}

十、綜合優(yōu)化配置示例

const path = require('path');
const os = require('os');
const webpack = require('webpack');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = {
  mode: 'development',
  devtool: 'eval-cheap-module-source-map',
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'thread-loader',
            options: {
              workers: os.cpus().length - 1
            }
          },
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HardSourceWebpackPlugin(),
    new webpack.ProgressPlugin(),
    process.env.ANALYZE && new BundleAnalyzerPlugin()
  ].filter(Boolean),
  resolve: {
    alias: {
      '@': path.resolve('src')
    },
    extensions: ['.js', '.json']
  },
  optimization: {
    removeAvailableModules: false,
    removeEmptyChunks: false,
    splitChunks: false,
    minimize: false
  },
  stats: {
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false
  }
};

關(guān)鍵優(yōu)化指標(biāo)對(duì)比

優(yōu)化手段構(gòu)建時(shí)間減少幅度適用場景
HardSourceWebpackPlugin60%-80%開發(fā)環(huán)境
thread-loader30%-50%大型項(xiàng)目
DLL 預(yù)編譯40%-60%穩(wěn)定第三方庫
SWC/esbuild50%-70%全場景
緩存配置70%-90%增量構(gòu)建

最佳實(shí)踐建議

  • 分層優(yōu)化

    • 開發(fā)環(huán)境:側(cè)重構(gòu)建速度(緩存、不壓縮)
    • 生產(chǎn)環(huán)境:側(cè)重輸出質(zhì)量(Tree Shaking、壓縮)
  • 漸進(jìn)式實(shí)施

1. 添加基礎(chǔ)緩存(HardSourceWebpackPlugin)
2. 引入多進(jìn)程(thread-loader)
3. 分析優(yōu)化重點(diǎn)(SpeedMeasurePlugin)
4. 實(shí)施高級(jí)優(yōu)化(DLL/SWC)

持續(xù)監(jiān)控

  • 記錄每次構(gòu)建時(shí)間
  • 設(shè)置性能預(yù)算
performance: {
  hints: 'warning',
  maxAssetSize: 500 * 1024,
  maxEntrypointSize: 500 * 1024
}

通過綜合應(yīng)用這些優(yōu)化策略,可以將 Webpack 構(gòu)建速度提升 3-10 倍,顯著改善開發(fā)體驗(yàn)。建議根據(jù)項(xiàng)目實(shí)際情況選擇性組合使用,并定期使用分析工具評(píng)估優(yōu)化效果。

以上就是Webpack打包速度優(yōu)化方案匯總的詳細(xì)內(nèi)容,更多關(guān)于Webpack打包速度優(yōu)化的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論