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

React项目懒加载失效求助:构建后仅生成单个JS文件

为什么React路由懒加载项目构建后只生成一个JS文件?

项目情况

我有一个配置了路由且所有页面都使用懒加载组件的项目,执行npm run build命令后仅生成一个JS文件,但同样采用懒加载的小型测试项目构建后能生成4个JS文件,想知道这一差异的原因。

路由组件示例

export const RoutersComponent = () => {
  return (
    <HashRouter basename={'/'}>
      <Routes>
        <Route
          path="/"
          element={<Navigate replace to={routerConfig.log.url} />}
        />
        <Route
          path={routerConfig.reg.url}
          element={<LazyRegistrationPage />}
        />
        <Route
          path={routerConfig.log.url}
          element={<LazyLogginPage />}
        />
      </Routes>
    </HashRouter>
  )
}

完整路由组件见项目src/router.js文件

懒加载组件示例

src/pages/registration下的index.js:

export * from './registration'
export * from './lazy'

lazy.js文件:

import { Suspense, lazy } from 'react'
import { Loading } from '../../components'

const Registration = lazy(() =>
  import('./registration').then((module) => ({
    default: module.Registration
  }))
)

export const LazyRegistrationPage = () => {
  return (
    <Suspense fallback="Loading...">
      <Registration />
    </Suspense>
  )
}

registration.js简化内容:

export const Registration = () => {
  return (
    <section className="log">
      Registration
    </section>
  )
}

完整注册组件见项目src/pages/registration目录

使用的依赖版本

"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^6.3.0",

测试项目对比

小型测试项目的懒加载功能正常工作,构建后生成4个JS文件,核心代码如下:

import { Suspense, lazy } from "react";
import "./App.css";

const A = lazy(() =>
  import("./A").then((module) => ({
    default: module.A,
  }))
);

const LazyA = () => {
  return (
    <Suspense fallback="loading...">
      <A />
    </Suspense>
  );
};

const B = lazy(() => import("./B"));

const LazyB = () => {
  return (
    <Suspense fallback="loading...">
      <B />
    </Suspense>
  );
};

function App() {
  return (
    <>
      <div className="App">hello</div>
      <LazyA />
      <LazyB />
    </>
  );
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:35:00