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`;
    }
相关推荐
IT_陈寒20 小时前
Python 3.11性能翻倍秘诀:7个你从未注意过的隐藏优化点!
前端·人工智能·后端
学习编程的Kitty20 小时前
算法——位运算
java·前端·算法
程序猿阿伟21 小时前
《3D动作游戏受击反馈:从模板化硬直到沉浸式打击感的开发拆解》
前端·网络·3d
jsonchao21 小时前
web 菜鸟级选手,纯好玩,做了 1 个小游戏网站(我感觉挺好玩😂)
前端
Onion21 小时前
解决 iframe 中鼠标事件丢失问题:拖拽功能的完整解决方案
前端·javascript·vue.js
Sailing21 小时前
🔥🔥「别再复制正则了」用 regex-center 一站式管理、校验、提取所有正则
前端·javascript·面试
GISer_Jing21 小时前
前端知识详解——HTML/CSS/Javascript/ES5+/Typescript篇/算法篇
前端·javascript·面试
一枚前端小能手21 小时前
🔧 jQuery那些经典方法,还值得学吗?优势与式微的真相一次讲透
前端·javascript·jquery
写不来代码的草莓熊21 小时前
vue前端面试题——记录一次面试当中遇到的题(4)
前端·javascript·vue.js·面试
Ratten21 小时前
【uniapp】---- 在 uniapp 实现 app 的版本检查、下载最新版本、自动安装
前端