在 TypeScript 项目里,ESLint 是能支持 子路径模块导入(path alias) 的,只是需要一些额外配置,否则 ESLint 可能会报类似 Unable to resolve path to module '@/utils'
的错误。
📌 实现思路
子路径导入依赖 TypeScript 的 paths
配置 + ESLint 的解析器配置。
1. 在 tsconfig.json
中配置 paths
例如:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@/*": ["*"]
}
}
}
这样就可以在代码里写:
import { formatDate } from "@/utils/date";
2. 安装 ESLint 相关依赖
需要的解析器和插件:
npm install -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-import-resolver-typescript
3. 配置 .eslintrc.js
关键是 告诉 ESLint 如何解析 TS 的路径别名:
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json', // 确保 ESLint 知道 TS 配置
},
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:import/typescript'
],
settings: {
'import/resolver': {
// 让 ESLint 解析 TS paths
typescript: {
alwaysTryTypes: true,
project: './tsconfig.json'
}
}
},
rules: {
// 例子:禁止未解析的 import
'import/no-unresolved': 'error'
}
};
4. 可能遇到的问题
VSCode ESLint 插件没生效
需要在 VSCode 里重启 ESLint 服务,或者npm run lint
直接跑一下。路径没解析
确认tsconfig.json
的baseUrl
和paths
正确,并且.eslintrc.js
里import/resolver
配置到了typescript
。
✅ 总结
- TypeScript 负责告诉编译器怎么找子路径(
tsconfig.json
)。 - ESLint 要用
eslint-import-resolver-typescript
来同步解析。 - 配置好后,ESLint 就能支持
@/xxx
这种子路径导入,并能正确报错或补全。