React项目启动报错:SyntaxError: Unexpected token 'export' 求助
解决React + TypeScript项目中
SyntaxError: Unexpected token 'export'的常见问题 1. 先查TypeScript配置文件(tsconfig.json)
这是最容易踩坑的点,确保配置能正确处理ES模块:
- 把
compilerOptions里的module设为ESNext或ES6(React项目基本用这个),同时开启esModuleInterop避免模块兼容问题:
{ "compilerOptions": { "module": "ESNext", "target": "ES6", "moduleResolution": "NodeNext", "esModuleInterop": true, "allowJs": true, "jsx": "react-jsx" }, "include": ["src/**/*"] }
- 确认
include字段覆盖了所有源码文件(比如src下的.ts/.tsx),别漏了你的接口定义文件。
2. 核对文件扩展名
- TypeScript组件必须用
.tsx扩展名(因为包含JSX),接口/工具文件用.ts,别写成.js——如果你的IJob接口文件是.js,立马改成.ts。 - 要是导入时习惯省略扩展名,得确保工具链能自动解析
.ts/.tsx:比如Create React App、Vite默认支持,自定义webpack的话要在resolve.extensions里加上这些后缀:
// webpack.config.js resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] }
3. 别混用模块语法
- 统一用ES模块的
export/import,别在同一个文件里混写module.exports(CommonJS语法)和export default,比如:
// 正确写法:IJob.ts export interface IJob { id: number; title: string; } // 正确写法:Job.tsx import { IJob } from './IJob'; export default function Job({ job }: { job: IJob }) { return <div>{job.title}</div>; }
4. 检查脚手架配置
- 如果你是手动加的TypeScript,不如直接用官方模板重建项目:
npx create-react-app my-app --template typescript,避免手动配置遗漏。 - Vite项目的话,确保
vite.config.ts里装了@vitejs/plugin-react插件,它会自动处理TS/TSX文件:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()] });
5. 清理依赖缓存
- 删了
node_modules和pnpm-lock.yaml,重新跑pnpm install——有时候依赖版本不兼容或者缓存出问题也会导致这种语法错误。 - 确保
typescript、@types/react、@types/react-dom的版本匹配,比如TypeScript至少要4.5以上,别用太老的版本。
6. 测试文件的额外配置
如果错误来自测试文件,得给测试框架(比如Jest)加TS支持:
- 安装
ts-jest和@types/jest,然后在jest.config.js里加配置:
module.exports = { preset: 'ts-jest', testEnvironment: 'jsdom', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'] };
内容的提问来源于stack exchange,提问作者user989988
相关产品推荐
相关产品推荐

