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`;
    }
相关推荐
FRing0334 分钟前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
Bczheng138 分钟前
组件化服务端渲染模式SSR
前端
whitelbwwww2 小时前
CUDA C++实战--中级
开发语言·前端·c++
张紫娃2 小时前
Chrome插件-Stylus(屏蔽博客广告)
前端·chrome·stylus
Yannik2 小时前
在 Apple Silicon Mac 上用 Jenkins + Fastlane 搭建 iOS CI:从自动打包到 MR 检查流水线的完整实践
前端
Nayana2 小时前
《Web 到 HarmonyOS》-- 打包:Vite 产物 → HAP / HAR / HSP
前端
inksci3 小时前
用飞帆做了个小网页
前端·javascript·css·html
去伪存真3 小时前
被 pnpm 打包坑惨后,我彻底盘明白了硬链接与软链接
前端·electron
zhensherlock3 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
tryCbest8 小时前
Vue3——第 22 篇:Pinia——新一代状态管理(上)
前端·javascript·vue.js