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

使用Create React App搭建TS项目遇TS2691与TS1208错误求助

解决TypeScript React项目的两个编译错误

错误1:TS2691 导入路径不能以'.tsx'结尾

解决方法

在App.tsx中去掉导入语句里的.tsx后缀,TypeScript会自动识别项目中的.tsx模块:
修改前:

import Header from './components/header.tsx';
import Main from './components/main.tsx';
import Footer from './components/footer.tsx';

修改后:

import Header from './components/header';
import Main from './components/main';
import Footer from './components/footer';

错误2:TS1208 header.tsx在'--isolatedModules'模式下无法编译

解决方法

该错误是因为header.tsx未被标记为ES模块,--isolatedModules模式要求所有文件必须包含导入或导出语句:

  • 若header.tsx中有Header组件,确保添加导出语句:
    function Header() {
      // 组件内容
    }
    export default Header;
    
  • 若文件仅包含全局代码无组件,添加空导出转为模块:
    export {};
    

额外修复:package.json中的build命令问题

你的package.json里的build命令使用了tsc,不符合create-react-app TypeScript模板的默认配置,会导致编译规则不匹配,改回默认命令:
修改前:

"build": "tsc",

修改后:

"build": "react-scripts build",

完成以上修改后,重新运行npm start或npm run build即可解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:42:36