Next.js+TypeScript项目如何解决ESLint报TS2307绝对路径导入错误?
解决Next.js+TypeScript绝对路径导入的ESLint TS2307错误
一、能不能直接忽略TS2307错误?
能,但真心不推荐——这会把真正的模块缺失问题也一并掩盖,真出问题时你根本没法排查。如果实在要临时这么做,有两种方式:
- 在ESLint配置里关闭检查
打开项目根目录的.eslintrc.json(或.eslintrc.js),在rules中添加:
{ "rules": { // 关闭模块未找到的ESLint检查 "import/no-unresolved": "off", // 禁用TypeScript对应TS2307的相关检查 "@typescript-eslint/no-unsafe-import": "off" } }
- 在TypeScript配置里忽略错误
修改tsconfig.json的compilerOptions:
{ "compilerOptions": { "noImplicitAny": false, "skipLibCheck": true, "suppressImplicitAnyIndexErrors": true } }
当然你也可以在每个导入行加// @ts-ignore,但48个错误一个个加太折腾,不建议这么做。
二、推荐做法:从根源解决(配置路径映射)
Next.js能识别/指向src,但TypeScript和ESLint没跟上,只要配置路径映射让它们统一认知,错误自然就消失了:
- 修改
tsconfig.json
在compilerOptions中添加baseUrl和paths:
{ "compilerOptions": { "baseUrl": "./src", // 把所有以/开头的导入映射到src目录下对应路径 "paths": { "/*": ["*"] }, // 以下是原有配置,无需改动 "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] }
- 让ESLint识别路径映射
先安装依赖:
npm install eslint-import-resolver-typescript --save-dev
然后在.eslintrc.json中添加配置:
{ "settings": { "import/resolver": { "typescript": { "project": "./tsconfig.json" } } }, "extends": [ "next/core-web-vitals", "plugin:@typescript-eslint/recommended" ] }
这样配置完成后,TypeScript和ESLint都会正确识别/指向src的绝对路径,TS2307错误会全部消失,还不会错过真正的模块缺失问题。
内容的提问来源于stack exchange,提问作者Pexate
相关产品推荐
相关产品推荐

