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`;
    }
相关推荐
小米渣的逆袭4 小时前
Chrome Extension Script World(ISOLATED / MAIN)原理与适用场景
前端·javascript·chrome
微信开发api-视频号协议5 小时前
Codex++安全边界探秘:从模型能力到风险防御
前端·安全·微信·企业微信
想你依然心痛5 小时前
AtomCode 在前端开发中的实战体验:React + TypeScript 项目开发实录
前端·react.js·typescript
疯狂的魔鬼5 小时前
精确计算容器剩余视口高度:useAutoContainerFullHeight 的工程实践
前端·css·typescript
用户059540174465 小时前
用了 3 个月 ChatGPT,才发现它一直在遗忘——用 Playwright 自动化验证记忆存储一致性
前端·css
玄玄子5 小时前
xss前端解决方案
前端·浏览器·xss
林希_Rachel_傻希希5 小时前
web性能优化之——AI总结视频
前端·javascript·面试
前端炒粉5 小时前
个人简历面经总结二
前端·网络·vue.js·react.js·面试
用户059540174466 小时前
用了半年 LangChain Memory,才发现回滚测试压根没测对
前端·css
木木的木云6 小时前
从零构建微前端框架:PavilionMfe 设计揭秘
前端·架构·vite