【问题标题】:How to tell eslint that you prefer single quotes around your strings如何告诉 eslint 你更喜欢在你的字符串周围加上单引号
【发布时间】:2015-06-01 12:08:09
【问题描述】:

我是 eslint 的新手,它吐出大量错误告诉我使用双引号:

error  Strings must use doublequote

这不是我的偏好。我已经建立了一个基本的 .eslintrc 文件:

{
  "env": {
    "node": 1
  }
}

我想将其配置为单引号。

【问题讨论】:

    标签: node.js eslint


    【解决方案1】:

    http://eslint.org/docs/rules/quotes.html

    {
      "env": {
        "node": 1
      },
      "rules": {
        "quotes": [2, "single", { "avoidEscape": true }]
      }
    }
    

    【讨论】:

    • 如果我需要使用单引号或双引号,上面的规则有什么改变?
    • @Antonius Bloch,这个解决方案在我的 Vue.js 项目中不起作用..."eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "@vue/prettier" ], "rules": { "no-console": "off", "quotes": [1, "single", { "avoidEscape": true }] },
    • 2 是干什么用的?我在那个链接中看不到任何解释。
    • @ryan2johnson9 这是一个规则严重性级别:0 = 关闭,1 = 警告,2 = 错误
    【解决方案2】:

    如果您使用的是 TypeScript/ES6,您可能希望包含模板文字(反引号)。此规则首选单引号,并允许使用模板文字。

    TypeScript 示例

    "@typescript-eslint/quotes": [
      "error",
      "single",
      {
        "allowTemplateLiterals": true
      }
    ]
    

    另一个有用的选项是允许单引号或双引号,只要字符串包含可转义的引号,例如 "lorem ipsum 'donor' eta"'lorem ipsum "donor" eta'

    "@typescript-eslint/quotes": [
      "error",
      "single",
      {
        "avoidEscape": true,
        "allowTemplateLiterals": true
      }
    ]
    

    参考资料:

    ESLint

    https://eslint.org/docs/rules/quotes

    TypeScript ESLint

    https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/quotes.md

    【讨论】:

    • 我认为您不需要将allowTemplateLiterals 设置为true,除非您希望允许使用模板文字字符串,即使只有单引号可以使用。默认情况下允许使用模板文字。这很容易测试。
    • 帖子中的两个示例与allowTemplateLiterals 的示例完全相同,非常令人困惑。在确定之前投反对票。
    • @oyalhi 是的,不知何故错过了avoidEscape。谢谢
    • 感谢您的更新。赞成。
    【解决方案3】:
    rules: {
      'prettier/prettier': [
        'warn',
        {
          singleQuote: true,
          semi: true,
        }
      ],
    },
    

    在版本"eslint": "^7.21.0"

    【讨论】:

    • 能否请您添加更多信息,说明为什么它成为可能?
    • ...以及为什么它是必要的(= 为什么来自 @typescript-eslint 包的 eslint 修复程序不够用)
    【解决方案4】:

    对于 jsx 字符串,如果您想为所有文件设置此规则,请在 eslint 配置文件中创建该规则。

      rules: {
        'jsx-quotes': [2, 'prefer-single'],
      }
    

    或'prefer-double' 表示双引号。

    【讨论】:

      【解决方案5】:

      如果您还想允许双引号,如果它们会避免在字符串中转义单引号,并允许模板文字(合理的默认值,imo),请尝试以下操作:

      {
        "env": {
          "node": 1
        },
        "rules": {
          "quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }]
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2013-12-24
        • 2018-03-09
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 1970-01-01
        相关资源
        最近更新 更多