ESLint矛盾报错:要求添加分号却提示分号多余
ESLint分号规则冲突问题解决
问题现象
每次运行lint脚本扫描代码时,ESLint会抛出缺少分号的错误;但添加缺失的分号后再次运行ESLint,又会在同一文件的相同行抛出分号多余的错误,该问题出现在所有导入语句和导出语句上。
示例代码
import { atom } from 'recoil'; import { OrderItemType } from '../types/OrderItemType'; export const orderItemsAtom = atom<OrderItemType[]>({ key: 'values', default: [] });
当前ESLint配置(.eslint.json)
{ "env": { "browser": true, "es2021": true }, "extends": [ "plugin:react/recommended", "standard-with-typescript" ], "overrides": [ ], "parserOptions": { "ecmaVersion": "latest", "sourceType": "module", "project": ["./tsconfig.json"] }, "plugins": [ "react" ], "rules": { "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ], "no-prototype-builtins": "off", "react/jsx-handler-names": "off", "@typescript-eslint/no-explicit-any": "off", "import/prefer-default-export": "off", "import/no-cycle": "off", "react/jsx-props-no-spreading": "off", "@typescript-eslint/no-shadow": "off", "no-param-reassign": "off", "react/no-array-index-key": "off", "no-nested-ternary": "off", "react/require-default-props": "off", "no-plusplus": "off", "no-useless-return": "off", "no-useless-escape": "off", "react/destructuring-assignment": "off", "class-methods-use-this": "off", "react/jsx-no-useless-fragment": "off" }, "settings": { "react": { "version": "detect" } } }
问题原因
- 规则集冲突:你继承的
standard-with-typescript规则集内置了不要求分号的规则(对应@typescript-eslint/semi: ["error", "never"]),但你手动在rules里设置了原生ESLint的semi: ["error", "always"],两者规则矛盾。 - 规则优先级问题:对于TypeScript文件,
@typescript-eslint/semi规则的优先级高于原生ESLint的semi规则,导致两种规则交替触发错误提示。
解决方法
方法一:统一使用TypeScript专属分号规则
删除rules中的原生semi配置,替换为@typescript-eslint/semi规则,明确指定分号要求:
"rules": { // 其他规则保持不变 "@typescript-eslint/semi": ["error", "always"] }
方法二:遵循Standard风格规则
直接移除自己设置的semi规则,完全使用standard-with-typescript自带的无分号规则,代码中不再添加分号。
方法三:调整规则继承顺序(不推荐)
将自定义规则的优先级提高,把standard-with-typescript放在extends数组的最后,让自定义规则覆盖继承规则,但这种方式可能引发其他潜在冲突,不如方法一可靠。
内容的提问来源于stack exchange,提问作者Daniel Corona
相关产品推荐
相关产品推荐

