You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prettier与ESLint引号规则冲突排查:TS/JS单引号JSX双引号

冲突原因分析

  1. ESLint配置语法错误:你的rules对象提前闭合,导致camelcase、arrow-parens规则配置无效,同时可能干扰其他规则的正常解析。
  2. 引号规则冲突:
    • 原生ESLint的quotes: [2, "single"]会强制所有字符串(包括JSX属性内的字符串)使用单引号,和你期望的JSX用双引号需求矛盾。
    • 虽然配置了jsx-quotes: [2, "prefer-double"],但该规则仅控制JSX属性的引号格式,无法覆盖JSX内部表达式中的字符串规则,而Prettier的jsxSingleQuote: false要求JSX语境用双引号,两者形成冲突。

修复步骤

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:20:54