Next.js项目JSX与TSX共存时出现模块找不到错误求助
解决Next.js添加TSX后@components路径解析失败的问题
我用JSX创建了Next.js项目,添加TSX文件后,Next.js自动生成了tsconfig.json,但出现模块找不到的错误:
./app/layout.jsx:2:0 Module not found: Can't resolve '@components/navegador/Nav' 1 | import './globals.scss'; > 2 | import Nav from '@components/navegador/Nav'; 3 | import Foot from '@components/footer/Foot'; 4 | 5 | export const metadata = {
这些组件都是JSX格式的。删除tsconfig.json后错误消失,但TSX文件会报错。我的tsconfig.json内容如下:
{ "compilerOptions": { "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "strict": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "incremental": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "plugins": [ { "name": "next" } ] }, "include": [ "next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx" ], "exclude": [ "node_modules" ] }
问题根源
自动生成的tsconfig.json缺少路径别名配置,导致TypeScript无法识别@components这类自定义别名;删掉tsconfig后,Next.js用默认JS解析规则能识别别名,但TSX文件又失去了TypeScript语法支持,陷入两难。
修复步骤
- 给tsconfig添加路径别名配置
在compilerOptions里加入baseUrl和paths(假设你的components文件夹在项目根目录):
"compilerOptions": { // ... 保留原有配置 "baseUrl": ".", "paths": { "@components/*": ["components/*"] } }
- 让include覆盖JS/JSX文件
原来的include只包含TS/TSX文件,需要补充JS/JSX类型,让TypeScript能处理这些文件:
"include": [ "next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx" ]
- 重启开发服务器
修改配置后必须重启Next.js开发服务器,新配置才能生效。
这样调整后,TypeScript既能识别@components路径别名,又能正常处理JSX和TSX文件,两种错误都会消失。
内容的提问来源于stack exchange,提问作者sistemas13
相关产品推荐
相关产品推荐

