React項目引用antd,優化之項目大小縮減5倍的配置方案(gzip福利)


react 項目根目錄新建config-overrides.js 並寫如下代碼,require引入的包可以使用yarn add 安裝

const { override, fixBabelImports, addWebpackPlugin } = require('customize-cra');
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
const { StatsWriterPlugin }  = require("webpack-stats-plugin");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;   //gzip 壓縮正則匹配
// module.exports = function override(config, env) {
//     // do stuff with the webpack config...
//     return config;
//   };
const CompressionWebpackPlugin = require('compression-webpack-plugin');   //這是gzip壓縮插件,本地壓縮后到線上訪問很快
// module.exports = function override(config, env) {
//     // do stuff with the webpack config...
//     return config;
//   };
let startTime = Date.now();
if(process.env.NODE_ENV === 'production') process.env.GENERATE_SOURCEMAP = "false";
// 自定義生產環境配置
const productionConfig =()=> (config) =>{
  if(config.mode === 'production'){
      config.plugins.push(...[
          new StatsWriterPlugin({
              fields: null,
              transform: (data) => {
                let endTime = Date.now()
                data = {
                  Time: (endTime - startTime)/1000 + 's'
                }
                return JSON.stringify(data, null, 2);
              }
          }),
          new BundleAnalyzerPlugin()
      ])
  }
  return config
}
// 打包配置
const compressGzip =()=>  config => {
  if (config.mode === 'production') {
    // 添加js打包gzip配置
    config.plugins.push(
      new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: productionGzipExtensions,
        threshold: 0,
        minRatio: 0.8,
        deleteOriginalAssets: false
      }),
    )
  }
  return config;
}
module.exports = override(
  productionConfig,
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: 'css',
  }),
  compressGzip,
  addWebpackPlugin(new AntdDayjsWebpackPlugin())
);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM