使用Typegoose时遭遇ESLint检测问题,求解决方案
解决Typegoose装饰器的ESLint检测问题
当前依赖版本
typescript: ^4.8.2@typescript-eslint/eslint-plugin: ^2.34.0@typescript-eslint/parser: ^2.34.0eslint: ^6.5
现有ESLint配置
--- # Env Vars # env: es6: true node: true ignorePatterns: - "!.*" - "**/node_modules/.*" # Parser vars # parser: "@typescript-eslint/parser" parserOptions: ecmaVersion: 2018 # Plugins # plugins: - "@typescript-eslint" - mongodb extends: - plugin:@typescript-eslint/recommended # Rules # rules: indent: - 1 - tab - SwitchCase: 1 no-undef: 2 no-unreachable: 2 no-unused-expressions: 1 no-unused-vars: 0 comma-dangle: - 1 - only-multiline no-multi-spaces: - 1 - exceptions: VariableDeclarator: true no-shadow-restricted-names: 0 eqeqeq: - 1 - smart no-dupe-keys: 2 no-duplicate-case: 2 no-extra-semi: 2 max-depth: - 1 - 4 no-empty: 2 "@typescript-eslint/no-var-requires": off "@typescript-eslint/explicit-function-return-type": off "@typescript-eslint/no-explicit-any": off "@typescript-eslint/ban-ts-ignore": off "@typescript-eslint/interface-name-prefix": off "@typescript-eslint/class-name-casing": off "@typescript-eslint/no-use-before-define": - error - functions: false classes: true "@typescript-eslint/no-extra-parens": 2 "@typescript-eslint/ban-ts-comment": 0
遇到的问题
1. 装饰器被标记为未使用
错误提示:error 'index' is defined but never used
对应代码:
import { index } from '@typegoose/typegoose'; @index({ user: 1, deleted: 1, facility: 1, provider: 1, }, { background: true, })
2. 装饰器参数缩进异常
警告提示:warning Expected indentation of 1 tab but found 0
ESLint强制的不美观格式:
@index({ user: 1, deleted: 1, facility: 1, provider: 1, }, { background: true, })
解决方案
解决未使用变量错误
ESLint默认无法识别TypeScript装饰器的使用场景,只需在@typescript-eslint/no-unused-vars规则中开启ignoreDecorated选项,就能让ESLint忽略装饰器的“未使用”检测:
修改.eslintrc.yml的rules部分:
"@typescript-eslint/no-unused-vars": - error - ignoreDecorated: true
这样既保留了对普通变量的未使用检测,又能正确识别装饰器的使用。
解决缩进格式问题
原生indent规则对TypeScript装饰器的支持不佳,替换为@typescript-eslint/indent规则即可解决:
- 先禁用原生
indent规则:
indent: off
- 添加
@typescript-eslint/indent规则,保持你的tab缩进配置:
"@typescript-eslint/indent": - 1 - tab - SwitchCase: 1
该规则会自动正确处理装饰器参数的缩进,让代码保持你想要的美观格式。
最终调整后的关键规则片段
rules: indent: off "@typescript-eslint/no-unused-vars": - error - ignoreDecorated: true "@typescript-eslint/indent": - 1 - tab - SwitchCase: 1 # 其他原有规则...
内容的提问来源于stack exchange,提问作者Bárbara Pegoraro Markus
相关产品推荐
相关产品推荐

