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

React开发服务器在子目录运行异常:bundle.js路径错误致空白页

解决Create React App开发服务器子目录下bundle.js路径错误问题

问题分析

你当前配置中,bundle.js仍指向根目录,是因为开发环境下REACT_APP_PUBLIC_URL设置了完整URL,而Create React App的开发服务器只会识别相对子目录路径作为资源前缀,无法处理完整域名URL。

修正步骤

  1. 修改.env配置
    将REACT_APP_PUBLIC_URL改为子目录相对路径,同时新增原生支持的PUBLIC_URL变量(开发服务器会读取该变量生成bundle路径):

    PUBLIC_URL=/proxy/port/subdirectory
    REACT_APP_PUBLIC_URL=/proxy/port/subdirectory
    
  2. 调整Router的basename
    保持原代码结构不变,变量值已改为相对路径,符合Router basename的要求(basename是域名后的路径前缀,无需完整URL):

    import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
    import ReactDOM from 'react-dom/client';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <Router basename={process.env.REACT_APP_PUBLIC_URL}>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </Router>
    );
    
  3. 更新index.html的base标签与资源引用
    改用Create React App原生的%PUBLIC_URL%变量,无需自定义的REACT_APP_前缀:

    <base href="%PUBLIC_URL%" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    
  4. 重启开发服务器
    环境变量修改后需要重启才能生效,重新执行启动命令:

    HOST=localhost npm start
    

原理说明

开发环境下,Create React App的dev-server仅识别相对路径形式的资源前缀,完整URL会被忽略,导致bundle.js仍使用根路径。通过设置PUBLIC_URL为子目录相对路径,dev-server会自动为所有静态资源(包括bundle.js)添加该前缀,确保资源正确加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:45:47