Prettier与ESLint引号规则冲突排查:TS/JS单引号JSX双引号
冲突原因分析
- ESLint配置语法错误:你的
rules对象提前闭合,导致camelcase、arrow-parens规则配置无效,同时可能干扰其他规则的正常解析。 - 引号规则冲突:
- 原生ESLint的
quotes: [2, "single"]会强制所有字符串(包括JSX属性内的字符串)使用单引号,和你期望的JSX用双引号需求矛盾。 - 虽然配置了
jsx-quotes: [2, "prefer-double"],但该规则仅控制JSX属性的引号格式,无法覆盖JSX内部表达式中的字符串规则,而Prettier的jsxSingleQuote: false要求JSX语境用双引号,两者形成冲突。
- 原生ESLint的
修复步骤
1. 修正ESLint配置的语法错误并对齐引号规则
将camelcase和arrow-parens移到rules内部,同时用@typescript-eslint/quotes替代原生quotes规则,实现JS/TS单引号、JSX双引号的区分:
module.exports = { "extends": [ "react-app", "plugin:prettier/recommended", "plugin:import/typescript" ], "rules": { "arrow-body-style": 0, "react/prop-types": 0, "@typescript-eslint/no-non-null-assertion": 0, "@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/explicit-member-accessibility": 0, "@typescript-eslint/explicit-function-return-type": 0, "camelcase": 0, "arrow-parens": ["error", "as-needed"], "jsx-quotes": [2, "prefer-double"], "quotes": "off", // 禁用原生引号规则 "@typescript-eslint/quotes": [ "error", "single", { "jsx": "double", // 指定JSX语境用双引号 "allowTemplateLiterals": true // 允许模板字符串,可选 } ] }, "settings": { "polyfills": [ "Promise", "fetch", "Object", "Array.from", "URLSearchParams", "AbortController", "Headers" ], "react": { "version": "detect" } } }
2. 保留现有Prettier配置
你的Prettier配置已符合需求,无需修改:
module.exports = { "printWidth": 120, "trailingComma": "es5", "singleQuote": true, "jsxSingleQuote": false, "arrowParens": "avoid" }
3. 验证修复
运行以下命令自动修复代码并验证配置:
eslint --fix src/**/*.tsx prettier --write src/**/*.tsx
配置完成后,ESLint和Prettier将保持规则一致:JS/TS代码中的字符串用单引号,JSX语境(属性值、内部表达式字符串)用双引号,不再出现冲突报错。
内容的提问来源于stack exchange,提问作者alfredopacino
相关产品推荐
相关产品推荐

