Node ESLint转换相对路径自动加src前缀,与tsconfig设置不符
问题:ESLint转换相对导入为绝对路径时自动添加
src/前缀 我在client目录下执行npx eslint --fix src命令,希望通过git hook将代码中的相对导入转换为绝对路径,但转换后的路径自动添加了src/前缀,尽管已在compilerOptions中设置了baseUrl。
示例
原导入语句:
import { UserContext } from '../../services/userContext';
转换后结果:
import { UserContext } from 'src/services/userContext';
预期结果:
import { UserContext } from 'services/userContext';
项目目录结构
repo/ .eslintrc client/ tsconfig.json src/ <所有客户端代码与组件> server/
当前配置文件
.eslintrc(repo根目录)
// .eslintrc { "env": { "node": true, "commonjs": true }, "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint", "import", "no-relative-import-paths"], "extends": [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "plugin:import/recommended", "plugin:import/errors", "plugin:import/warnings", "plugin:import/typescript" ], "settings": { "import/resolver": { "typescript": { "project": [ "server/tsconfig.json", "client/tsconfig.json" ] }, "node": { "moduleDirectory": [ "client/src/", "client/node_modules", "server/src", "server/node_modules" ], "extensions": [".ts", ".tsx"] } } }, "rules": { "import/order": [ "warn", { "alphabetize": { "caseInsensitive": true, "order": "asc" }, "groups": [["builtin", "external"]], "newlines-between": "always" } ], "import/no-unresolved": [1, {"commonjs": false, "amd": false}], "@typescript-eslint/no-explicit-any": "off", "no-relative-import-paths/no-relative-import-paths": [ "warn", { "allowSameFolder": true } ] } }
client/tsconfig.json
{ "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "baseUrl": "src", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true, "jsx": "react-jsx", "lib": ["dom", "dom.iterable", "esnext"], "noEmit": true, "noFallthroughCasesInSwitch": true, "noImplicitAny": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "skipLibCheck": true, "strict": true, "target": "es5" }, "include": ["src"] }
问题原因与解决方案
问题出在no-relative-import-paths插件的默认行为:它默认以项目根目录为基准生成绝对路径,不会自动读取tsconfig的baseUrl配置,所以会把../../services/userContext转换为src/services/userContext(因为client/src在根目录下的路径是src)。
只需修改.eslintrc中的no-relative-import-paths规则配置,添加rootDir参数指定客户端代码的根目录client/src,插件就会基于这个目录生成不带src/前缀的绝对路径:
"no-relative-import-paths/no-relative-import-paths": [ "warn", { "allowSameFolder": true, "rootDir": "client/src" } ]
修改后重新执行npx eslint --fix src,导入路径就会符合预期的services/userContext格式。
内容的提问来源于stack exchange,提问作者jlarks32
相关产品推荐
相关产品推荐

