TypeScript React项目中ESLint无法识别tsconfig路径别名的问题
import/no-relative-parent-imports False Positives with TypeScript Path Aliases I get it, dealing with ESLint rules clashing with TypeScript path aliases is super frustrating. Let's break down why this is happening and fix it step by step:
1. Fix Your tsconfig.json Paths Syntax
First off, your current paths configuration has a tiny syntax issue that might be throwing things off. You wrote:
"paths": { "src/": ["./src/*"] }
That trailing slash after src is unnecessary. Change it to:
"paths": { "src/*": ["./src/*"] }
This tells TypeScript that any import starting with src/ maps directly to the ./src/ directory in your project root.
2. Explicitly Point ESLint to Your tsconfig.json
Even though you installed eslint-import-resolver-typescript, ESLint might not be automatically picking up your tsconfig (especially if your project has a non-standard structure). Update your .eslintrc.js to explicitly specify the project path:
module.exports = { // ... other ESLint config settings: { 'import/resolver': { typescript: { project: './tsconfig.json', // Path to your tsconfig file alwaysTryTypes: true // Optional: Ensures resolver checks for TypeScript files first }, }, }, };
This makes sure the resolver uses your exact tsconfig settings to resolve aliases, so ESLint recognizes src/components/ComponentA as an absolute alias import, not a relative parent import.
3. Clear ESLint Cache & Restart Your Linter
ESLint caches resolution results, so old, incorrect mappings might still be stuck. Clear the cache with:
npx eslint --clear-cache
Then restart your IDE's ESLint server (in VS Code, you can run the command "ESLint: Restart ESLint Server" from the command palette).
4. Verify Version Compatibility
Make sure all your related packages are on compatible versions. Outdated versions of eslint-plugin-import, eslint-import-resolver-typescript, or @typescript-eslint/eslint-plugin can cause weird resolution bugs. Run these commands to update to stable versions:
npm update eslint-plugin-import eslint-import-resolver-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser
Quick Troubleshooting Check
If you still see errors, double-check:
- You're not using a mix of relative imports and aliases in the same file (though that shouldn't cause this specific issue)
- Your tsconfig is in the project root (if it's in a subdirectory, adjust the
projectpath in.eslintrc.jsaccordingly, e.g.,./config/tsconfig.json) - You don't have conflicting resolver settings (like both
nodeandtypescriptresolvers enabled without proper prioritization)
After these steps, ESLint should correctly recognize your src/ aliases as valid absolute imports and stop throwing false positives for import/no-relative-parent-imports.
内容的提问来源于stack exchange,提问作者Paralyz3d

