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

将React组件后缀从.js改为.jsx后出现导出错误求助

React组件改为.jsx后缀后路由导入报错

问题背景

我是React初学者,之前组件用.js后缀,按建议改成.jsx(比如login.js改成login.jsx),但修改后配置路由时出现导入错误。

错误信息

Attempted import error: './components/Index' does not contain a default export (imported as 'Index').
ERROR in ./src/App.js 15:40-45
export 'default' (imported as 'Index') was not found in './components/Index' (module has no exports)

ERROR in ./src/App.js 26:40-55
export 'default' (imported as 'UserRegistation') was not found in './components/UserRegistation' (module has no exports)

ERROR in ./src/App.js 37:40-45
export 'default' (imported as 'Login') was not found in './components/Login' (module has no exports)

相关代码

App.js

import { BrowserRouter,Routes,Route } from "react-router-dom";
import Index from "./components/Index";
import UserRegistation from "./components/UserRegistation";
import Login from "./components/Login";

function App() {
  return (
   <div>
        <BrowserRouter>
            <Routes>
              <Route path="/" element= { <Index/>} />
              <Route path="/register" element= { <UserRegistation/>} />
              <Route path="/login" element= { <Login/>} />
            </Routes>
        </BrowserRouter>
   </div>
  );
}

export default App;

Login.jsx

<h1>Login</h1>

文件结构

React项目文件结构

解决方法

问题出在你的.jsx文件没有按照React规范定义和导出组件,直接写JSX片段无法被识别为可导入的组件。

  1. 修改组件文件:把每个.jsx文件的内容封装成函数组件,并添加默认导出。以Login.jsx为例:
function Login() {
  return <h1>Login</h1>;
}

export default Login;
  1. 批量修复其他组件:对Index.jsx和UserRegistation.jsx执行同样操作,确保每个组件都有函数定义和export default语句。
  2. 可选:明确导入后缀:打包工具一般能自动识别.jsx后缀,但也可以在App.js的导入语句里加上.jsx,让路径更清晰,比如import Login from "./components/Login.jsx";。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:35:32