如何告诉eslint您更喜欢字符串周围的单引号

Ant*_*och 17 node.js eslint

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

error  Strings must use doublequote
Run Code Online (Sandbox Code Playgroud)

那不是我的偏好.我有一个基本的.eslintrc文件设置:

{
  "env": {
    "node": 1
  }
}
Run Code Online (Sandbox Code Playgroud)

我想为单引号配置它.

Ant*_*och 30

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

{
  "env": {
    "node": 1
  },
  "rules": {
    "quotes": [2, "single", { "avoidEscape": true }]
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @ryan2johnson9 这是规则严重性级别:0 = 关闭,1 = 警告,2 = 错误 (5认同)
  • 如果我需要使用单引号或双引号,则上述规则有何变化? (4认同)
  • @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认同)
  • “2”有什么用?我在该链接中看不到任何解释。 (2认同)

Mo.*_*Mo. 7

rules: {
  'prettier/prettier': [
    'warn',
    {
      singleQuote: true,
      semi: true,
    }
  ],
},
Run Code Online (Sandbox Code Playgroud)

在版本 "eslint": "^7.21.0"


All*_*gwa 5

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

  rules: {
    'jsx-quotes': [2, 'prefer-single'],
  }
Run Code Online (Sandbox Code Playgroud)

或者用“prefer-double”表示双引号。


mtp*_*ltz 5

如果您使用的是 TypeScript/ES6,您可能需要包含模板文字(反引号)。此规则更喜欢单引号,并允许使用模板文字。

打字稿示例

"@typescript-eslint/quotes": [
  "error",
  "single",
  {
    "allowTemplateLiterals": true
  }
]
Run Code Online (Sandbox Code Playgroud)

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

"@typescript-eslint/quotes": [
  "error",
  "single",
  {
    "allowTemplateLiterals": true
  }
]
Run Code Online (Sandbox Code Playgroud)

参考:

ESLint

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

打字稿 ESLint

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

  • 我认为您不需要将“allowTemplateLiterals”设置为“true”,除非您希望允许使用模板文字字符串,即使只有单引号也可以。默认情况下允许使用模板文字。这可以很容易地进行测试。 (2认同)