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`;
    }
相关推荐
踩着两条虫9 分钟前
VTJ:DSL语言规范
前端·低代码·ai编程
广州华水科技12 分钟前
单北斗GNSS在水库形变监测中的应用与优势分析
前端
洲星河ZXH24 分钟前
JavaWeb,前端工程化
前端
子兮曰26 分钟前
独立开发者主流技术栈(2026最新)
前端·后端·全栈
踩着两条虫35 分钟前
VTJ.PRO 新手入门:从环境搭建到 AI 生成首个 Vue3 应用
前端·javascript·数据库·vue.js·人工智能·低代码
十有八七36 分钟前
Resume Agent P1 开发 — 记忆管理 + 用户配置 + 工具系统
前端·后端
2601_949816161 小时前
Node.js npm 安装过程中 EBUSY 错误的分析与解决方案
前端·npm·node.js
pancakenut1 小时前
自定义属性:从html到react
前端
hmh123451 小时前
录音与音频可视化
前端·javascript
ZC跨境爬虫1 小时前
3D 地球卫星轨道可视化平台开发 Day13(卫星可视化交互优化+丝滑悬停聚焦)
前端·算法·3d·json·交互