You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级react-scripts至v5后出现构建文件缺失问题

问题描述

将react-scripts升级至5版本后,执行build命令时出现构建异常,build文件夹中缺失main.[hash].chunk.js、main.[hash].chunk.css以及runtime-main.[hash].js文件。当前项目使用最新版本的craco进行配置,以下为升级前后的构建截图及craco配置代码:

升级前构建结果
升级后构建结果

Craco配置代码
const path = require('path');
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

module.exports = () => {
  const plugins = [];
  // if (process.env.NODE_ENV !== "production") {
  //   plugins.push(new BundleAnalyzerPlugin())
  // }

  return {
    eslint: {
      enable: true,
    },
    style: {
      css: {
        loaderOptions: (cssLoaderOptions, { env, paths }) => {
          cssLoaderOptions.modules = {
            localIdentName: "[local]_[hash:base64:5]",
          };
          return cssLoaderOptions;
        },
      },
    },
    webpack: {
      alias: {
        react: path.resolve(__dirname, '../node_modules', 'react'),
        'react-dom': path.resolve(__dirname, '../node_modules', 'react-dom'),
        'modernizr': path.resolve(__dirname, "./.modernizrrc.js")
      },
      plugins,
      configure: webpackConfig => {
        webpackConfig.resolve.fallback = {
          fs: false,
          path: require.resolve("path-browserify")
        };
        const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
          ({ constructor }) => constructor && constructor.name === 'ModuleScopePlugin'
        );
        webpackConfig.optimization= {
          chunkIds: 'natural',
        };        
        
        const [clientSrc] = webpackConfig.resolve.plugins[scopePluginIndex].appSrcs;
        const services = path.resolve(clientSrc, '../..');

        webpackConfig.resolve.plugins[scopePluginIndex].appSrcs.push(services);

        return webpackConfig;
      }
    },
    devServer: (devServerConfig, { env, paths, proxy, allowedHost }) => {
      devServerConfig = {
        server: {
          type: 'https'
        },
        https: undefined,
        onBeforeSetupMiddleware: undefined,
        onAfterSetupMiddleware: undefined
      };
      
      return devServerConfig;
    },
  }
};
解决方案

问题根源是你直接覆盖了webpackConfig.optimization对象。react-scripts v5的默认webpack配置中,optimization包含runtimeChunk: 'single'、splitChunks等关键设置,这些是生成main chunk和runtime chunk的核心配置。你直接赋值新对象会完全丢弃默认配置,导致构建异常。

只需修改配置方式,不替换整个optimization,仅修改指定属性:

// 替换原有的赋值代码
webpackConfig.optimization.chunkIds = 'natural';

这样既能保留你需要的chunkIds配置,又不会丢失react-scripts默认的优化规则,确保main chunk和runtime chunk正常生成。

另外建议确认craco版本与react-scripts v5完全兼容,避免其他兼容性问题。

内容的提问来源于stack exchange,提问作者ROBO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:55:23