react项目做的h5页面加载缓慢优化(3s优化到0.6s)

打包到生产环境时去掉SOURCEMAP

禁用生成 Source Map 是一种权衡,可以根据项目的实际需求和优化目标来决定是否禁用。如果您对调试需求不是特别强烈,可以考虑在生产构建中禁用 Source Map 以获取更好的性能。但如果需要保留调试能力,可以在生产构建中保留生成 Source Map

"buildProd": "BUILD_ENV=prod GENERATE_SOURCEMAP=false react-app-rewired build"

配置webpack进行相关优化

  1. 代码压缩,去掉log日志
cpp 复制代码
config.optimization.minimizer.push(
    new TerserPlugin({
      terserOptions: {
        compress: {
          drop_console: true,
        },
        output: {
          comments: false,
        },
      },
    })
  );
  1. 根据git版本生成输出目录
cpp 复制代码
const gitVersion = child_process.execSync('git rev-parse --short HEAD').toString().trim();
    const prePath = `${gitVersion}`
    const staticPath = `prePath`
    // 更改输出目录
    config.output.path = path.resolve(__dirname, `build/`);
    // js chunk asset
    config.output.filename = `${prePath}/js/[name].[contenthash:8].js`;
    config.output.chunkFilename = `${prePath}/js/[name].[contenthash:8].chunk.js`;
    config.output.assetModuleFilename = `${prePath}/media/[name].[hash][ext]`;
  1. CDN加速,开发环境和生产环境分开
cpp 复制代码
if (process.env.BUILD_ENV == "prod") {
      // 更改公共路径
      config.output.publicPath = `https://didbrowser-prod.oss-cn-chengdu.aliyuncs.com/`
    }
    if (process.env.BUILD_ENV == "dev") {
      config.output.publicPath = `https://didbrowser-dev.oss-cn-chengdu.aliyuncs.com/`
    }
  1. 对第三方插件大模块chunks 进行代码分割
cpp 复制代码
config.optimization = {
    ...config.optimization,
    splitChunks: {
      cacheGroups: {
        echarts: {
          test: /[\\/]node_modules[\\/]echarts[\\/]/, // 匹配 ECharts 模块
          name: 'echarts', // 生成的文件名
          chunks: 'all', // 对所有的 chunks 进行代码分割
        }
      },
    },
  };
  1. 更改 CSS 的输出路径
cpp 复制代码
const miniCssExtractPlugin = config.plugins.find(
        plugin => plugin instanceof MiniCssExtractPlugin
    );

    if (miniCssExtractPlugin) {
      miniCssExtractPlugin.options.filename = `${prePath}/css/[name].[contenthash:8].css`;
      miniCssExtractPlugin.options.chunkFilename = `${prePath}/css/[name].[contenthash:8].chunk.css`;
    }
相关推荐
行者全栈架构师22 分钟前
【鸿蒙心迹】让老照片变清晰:HarmonyOS 7.0 图像超分相册工程化落地与 5 个踩坑解法
架构·前端框架·开源
欣欣之王来了39 分钟前
原始HTML插值:v-html指令的使用与安全风险
前端·学习·架构·项目·vue3教程
IT_陈寒41 分钟前
Redis的LRU淘汰策略坑了我一整天
前端·人工智能·后端
计算机魔术师1 小时前
砍半价格、参数再涨,国产旗舰追到 Opus 鼻尖了
前端
特立独行的猫A1 小时前
10 MB 的桌面 AI 客户端:用仓颉 + 系统 WebView 替代 Electron
前端·harmonyos
修炼的dance2 小时前
白底图存JPG,sharp开mozjpeg背景杂点少近三成
前端
anOnion2 小时前
构建无障碍组件之Grid Pattern
前端·html·交互设计
乔旭伟2 小时前
Vben3 中后台表格封装实战:useVbenVxeGrid 的全局收敛与七个坑
前端·anti-design-vue·1024程序员节
鶴哥只手遮天3 小时前
jQuery 4.0 源码架构与工程实践-第 10 章 尺寸、几何与显隐
前端·javascript·jquery
Mia_墨黎3 小时前
2026 Windows 11 终端美化完全指南
前端·后端