Enforce the consistent use of either backticks, double, or single quotes
🔧 Fixable
Some problems reported by this rule are automatically fixable by the --fix
command line option
JavaScript allows you to define strings in one of three ways: double quotes, single quotes, and backticks (as of ECMAScript 6). For example:
/*eslint-env es6*/
var double = "double";
var single = 'single';
var backtick = `backtick`; // ES6 only
Each of these lines creates a string and, in some cases, can be used interchangeably. The choice of how to define strings in a codebase is a stylistic one outside of template literals (which allow embedded of expressions to be interpreted).
Many codebases require strings to be defined in a consistent manner.
Rule Details
This rule enforces the consistent use of either backticks, double, or single quotes.
Options
This rule has two options, a string option and an object option.
String option:
"double"
(default) requires the use of double quotes wherever possible"single"
requires the use of single quotes wherever possible"backtick"
requires the use of backticks wherever possible
Object option:
"avoidEscape": true
allows strings to use single-quotes or double-quotes so long as the string contains a quote that would have to be escaped otherwise"allowTemplateLiterals": true
allows strings to use backticks
Deprecated: The object property avoid-escape
is deprecated; please use the object property avoidEscape
instead.
double
Examples of incorrect code for this rule with the default "double"
option:
/*eslint quotes: ["error", "double"]*/
var single = 'single';
var unescaped = 'a string containing "double" quotes';
var backtick = `backntick`; // you can use n in single or double quoted strings
Examples of correct code for this rule with the default "double"
option:
/*eslint quotes: ["error", "double"]*/
/*eslint-env es6*/
var double = "double";
var backtick = `back
tick`; // backticks are allowed due to newline
var backtick = tag`backtick`; // backticks are allowed due to tag
single
Examples of incorrect code for this rule with the "single"
option:
/*eslint quotes: ["error", "single"]*/
var double = "double";
var unescaped = "a string containing 'single' quotes";
Examples of correct code for this rule with the "single"
option:
/*eslint quotes: ["error", "single"]*/
/*eslint-env es6*/
var single = 'single';
var backtick = `back${x}tick`; // backticks are allowed due to substitution
backticks
Examples of incorrect code for this rule with the "backtick"
option:
/*eslint quotes: ["error", "backtick"]*/
var single = 'single';
var double = "double";
var unescaped = 'a string containing `backticks`';
Examples of correct code for this rule with the "backtick"
option:
/*eslint quotes: ["error", "backtick"]*/
/*eslint-env es6*/
var backtick = `backtick`;
avoidEscape
Examples of additional correct code for this rule with the "double", { "avoidEscape": true }
options:
/*eslint quotes: ["error", "double", { "avoidEscape": true }]*/
var single = 'a string containing "double" quotes';
Examples of additional correct code for this rule with the "single", { "avoidEscape": true }
options:
/*eslint quotes: ["error", "single", { "avoidEscape": true }]*/
var double = "a string containing 'single' quotes";
Examples of additional correct code for this rule with the "backtick", { "avoidEscape": true }
options:
/*eslint quotes: ["error", "backtick", { "avoidEscape": true }]*/
var double = "a string containing `backtick` quotes"
allowTemplateLiterals
Examples of additional correct code for this rule with the "double", { "allowTemplateLiterals": true }
options:
/*eslint quotes: ["error", "double", { "allowTemplateLiterals": true }]*/
var double = "double";
var double = `double`;
Examples of additional correct code for this rule with the "single", { "allowTemplateLiterals": true }
options:
/*eslint quotes: ["error", "single", { "allowTemplateLiterals": true }]*/
var single = 'single';
var single = `single`;
{ "allowTemplateLiterals": false }
will not disallow the usage of all template literals. If you want to forbid any instance of template literals, use no-restricted-syntax and target the TemplateLiteral
selector.
When Not To Use It
If you do not need consistency in your string styles, you can safely disable this rule.
Version
This rule was introduced in ESLint v0.0.7.
Resources
- Rule source
- Tests source
title | layout |
---|---|
Rule quotes |
doc |
Enforce Quote Style (quotes)
JavaScript allows you to define strings in one of three ways: double quotes, single quotes, and backticks (as of ECMAScript 6). For example:
/*eslint-env es6*/ var double = "double"; var single = 'single'; var backtick = `backtick`; // ES6 only
Each of these lines creates a string and, in some cases, can be used interchangeably. The choice of how to define strings in a codebase is a stylistic one outside of template literals (which allow embedded of expressions to be interpreted).
Many codebases require strings to be defined in a consistent manner.
Rule Details
This rule is aimed at ensuring consistency of string quotes and as such will report a problem when an inconsistent style is found.
Fixable: This rule is automatically fixable using the --fix
flag on the command line.
The rule configuration takes up to two options:
- The first option is
"double"
,"single"
or"backtick"
for double-quotes, single-quotes or backticks respectively. The default is"double"
. - The second option is the
"avoid-escape"
flag. When using"avoid-escape"
, this rule will not report a problem when a string is using single-quotes or double-quotes so long as the string contains a quote that would have to be escaped otherwise. For example, if you specify"double"
and"avoid-escape"
, the string'He said, "hi!"'
is not considered a problem because using double quotes for that string would require escaping the double quotes inside of the string. This option is off by default.
When using "single"
or "double"
, template literals that don’t contain a substitution, don’t contain a line break and aren’t tagged templates, are flagged as problems, even with the "avoid-escape"
option.
Configuration looks like this:
[2, "single", "avoid-escape"]
The following patterns are considered problems:
/*eslint quotes: [2, "double"]*/ var single = 'single'; /*error Strings must use doublequote.*/ var unescaped = 'a string containing "double" quotes'; /*error Strings must use doublequote.*/
/*eslint quotes: [2, "single"]*/ var double = "double"; /*error Strings must use singlequote.*/ var unescaped = "a string containing 'single' quotes"; /*error Strings must use singlequote.*/
/*eslint quotes: [2, "double", "avoid-escape"]*/ var single = 'single'; /*error Strings must use doublequote.*/ var single = `single`; /*error Strings must use doublequote.*/
/*eslint quotes: [2, "single", "avoid-escape"]*/ var double = "double"; /*error Strings must use singlequote.*/ var double = `double`; /*error Strings must use singlequote.*/
/*eslint quotes: [2, "backtick"]*/ var single = 'single'; /*error Strings must use backtick.*/ var double = "double"; /*error Strings must use backtick.*/ var unescaped = 'a string containing `backticks`'; /*error Strings must use backtick.*/
/*eslint quotes: [2, "backtick", "avoid-escape"]*/ var single = 'single'; /*error Strings must use backtick.*/ var double = "double"; /*error Strings must use backtick.*/
The following patterns are not considered problems:
/*eslint quotes: [2, "double"]*/ /*eslint-env es6*/ var double = "double"; var backtick = `backntick`; // backticks are allowed due to newline var backtick = tag`backtick`; // backticks are allowed due to tag
/*eslint quotes: [2, "single"]*/ /*eslint-env es6*/ var single = 'single'; var backtick = `back${x}tick`; // backticks are allowed due to substitution
/*eslint quotes: [2, "double", "avoid-escape"]*/ var single = 'a string containing "double" quotes';
/*eslint quotes: [2, "single", "avoid-escape"]*/ var double = "a string containing 'single' quotes";
/*eslint quotes: [2, "backtick"]*/ /*eslint-env es6*/ var backtick = `backtick`;
/*eslint quotes: [2, "backtick", "avoid-escape"]*/ var double = "a string containing `backtick` quotes"
When Not To Use It
If you do not need consistency in your string styles, you can safely disable this rule.
Version
This rule was introduced in ESLint 0.0.7.
Resources
- Rule source
- Documentation source
Задать вопрос
@heIIfire
-
JavaScript
ESLint: Strings must use singlequote
-
Вопрос заданболее трёх лет назад
-
2114 просмотров
Комментировать
Подписаться
2
Оценить
Комментировать
Решения вопроса 0
Пригласить эксперта
Ответы на вопрос 1
@maxilamb
Frontend developer, lover of all new
"quotes": [
"error",
"single"
],
А вообще к любой либе есть документация
https://eslint.org/docs/rules/quotes
Ответ написан
более двух лет назад
Комментировать
Комментировать
Ваш ответ на вопрос
Войдите, чтобы написать ответ
Войти через центр авторизации
Похожие вопросы
-
-
JavaScript
- +2 ещё
Простой
Как настроить отправку файла на почту WordPress?
-
1 подписчик -
час назад
-
15 просмотров
1
ответ
-
-
-
JavaScript
Простой
Как правильно заполнить пустые свойства объекта данными, полученными из формы по одинаковому id?
-
1 подписчик -
час назад
-
30 просмотров
1
ответ
-
-
-
JavaScript
Простой
Как создать счетчик кликов для каждого элемента?
-
1 подписчик -
час назад
-
30 просмотров
3
ответа
-
-
-
JavaScript
Простой
Почему не добавляется новый класс к элементам html?
-
1 подписчик -
3 часа назад
-
26 просмотров
1
ответ
-
-
-
JavaScript
- +1 ещё
Средний
Как вызвать autoplay.stop и autoplay.start swiper?
-
1 подписчик -
7 часов назад
-
51 просмотр
0
ответов
-
-
-
JavaScript
Простой
Почему не работает Math.floor()?
-
1 подписчик -
7 часов назад
-
73 просмотра
1
ответ
-
-
-
JavaScript
- +2 ещё
Простой
Как в хроме используя JS взять содержимое вкладки Response?
-
2 подписчика -
8 часов назад
-
73 просмотра
1
ответ
-
-
-
JavaScript
- +2 ещё
Простой
Как сделать фото с камеры HTML js?
-
1 подписчик -
9 часов назад
-
77 просмотров
2
ответа
-
-
-
JavaScript
Средний
Как передать переменную в JSON.stringify()?
-
1 подписчик -
15 часов назад
-
61 просмотр
1
ответ
-
-
-
JavaScript
- +1 ещё
Средний
Как реализовать слайдер как на примере?
-
2 подписчика -
23 часа назад
-
116 просмотров
0
ответов
-
-
Показать ещё
Загружается…
Вакансии с Хабр Карьеры
Senior QA Automation (JavaScript)
4People
До 220 000 ₽
Middle JavaScript developer
Timeweb
•
Санкт-Петербург
До 200 000 ₽
PHP/JavaScript разработчик (Fullstack)
РСТ Энерджи
от 140 000 до 260 000 ₽
Ещё вакансии
Заказы с Хабр Фриланса
Подключить 8 методов API Yii2
12 февр. 2023, в 20:53
18000 руб./за проект
Разработать REST API на NEST.js с подключением модулей
12 февр. 2023, в 20:15
10000 руб./за проект
Создать программу с автоматическими действиями на виндовс
12 февр. 2023, в 20:14
100000 руб./за проект
Ещё заказы
Минуточку внимания
Присоединяйтесь к сообществу, чтобы узнавать новое и делиться знаниями
Зарегистрироваться
Войдите на сайт
Чтобы задать вопрос и получить на него квалифицированный ответ.
Войти через центр авторизации
Ekaterina Lopatina
Коллеги, день добрый. Код правильный, тест проходит. Но выводит другие ошибки.
// removed
Вот такие ошибки выводит
status: finished → Check your code. Linter failed.
/usr/src/app/babel.config.js
3:6 error Strings must use singlequote quotes
9:2 error Missing semicolon semi
10:1 error Too many blank lines at the end of file. Max of 0 allowed no-multiple-empty-lines
В чем проблем, помогите разобраться, пожалуйста
4
0
User 34bd397d50137a0f
Проблема, на мой взгляд начинающего программиста, заключается в том, что при использовании больше одного if, последующая конструкция if должна превратится в else if. То есть перед вторым и третьим if следует прописать слово else.
UPD Оказывается (посмотрел решение учителя), что и не нужно тут else if’ов :-). Тогда, что можно сказать, каждый if с новой строки начинать, а не продолжать после } (я так понимаю, ругается на плохую читаемость кода, что if’ы на одном уровне, а то, что выполняется должно быть на другом уровне; а получилось, что второй и третий if заняли места их же return’ов) И удалить пустую строку перед export.
0
Сергей К.
Екатерина, здравствуйте! Это отчёт работы линтера с описаниями стилистических ошибок. Их также нужно всегда исправлять. Давайте разберём, как работать с замечаниями линтера на примере простой ошибки: 9:2 error Missing semicolon semi
.
9:2
— строка и позиция, где по мнению линтера произошла ошибка;Missing semicolon
— описание ошибкиsemi
— название ошибки
Переведите и проанализируйте описание. При необходимости загуглите по названию ошибки semi eslint
и почитайте документацию с примерами. Исправьте ошибку и запустите повторную проверку линтера.
0
Ekaterina Lopatina
Я понимаю, что это нужно исправлять. Однако, я не понимаю что именно здесь нужно исправлять, ибо:
- 3:6 error Strings must use singlequote quotes
здесь и не должно быть «строки», почему он ругается что строка должна быть в кавычках? - 9:2 error Missing semicolon semi
строка 9, позиция 2 — это перед «}» зачем там «;»? - 10:1 error Too many blank lines at the end of file. Max of 0 allowed no-multiple-empty-lines
Если я удаляю последнюю пустую строку, то потом он ругается, что программа запрашивает новую строку, но не может обнаружить
/usr/src/app/finalGrade.js
15:27 error Newline required at end of file but not found eol-last
Поэтому я и прошу помощи разобраться, ведь даже запуская решение учителя, выдаются те же ошибки линтера
0
Сергей К.
Ого! Мы разобрали, как работать с линтером на примере ошибок системного файла. К вашему коду они не имеют отношения. Поправил ошибку в среде исполнения. Вам нужно получить последнюю версию практики, нажав кнопку Сброс, и после этого проработать замечания линтера повторно.
1
Problem/Motivation
Currently, we are using a mixture of single quotes and double quotes in our JavaScript, and I can’t see why. When I turn on eslint’s quotes rule set to single quotes, it only returns 215 errors; pretty small compared to turning on the eslint rule and setting it to double quotes: 4013 errors.
Our PHP standards for quotes are pretty clear: https://www.drupal.org/coding-standards#quotes
single quote strings should be used by default. Their use is recommended except in two cases:
- Deliberate in-line variable interpolation, e.g. «<h2>$header</h2>».
- Translated strings where one can avoid escaping single quotes by enclosing the string in double quotes. One such string would be «He’s a good person.» It would be ‘He’s a good person.’ with single quotes. Such escaping may not be handled properly by .pot file generators for text translation, and it’s also somewhat awkward to read.
In JavaScript, there is no such thing as #1. But we do have Drupal.t()
which can have strings with apostrophes.
So I think we should adopt the same rules for quotes in JavaScript as we already have for PHP.
Fortunately, eslint has a rule that will allow us to: always use single quotes, except when we use double quotes to avoid escaping a single quote or apostrophe in the string.
Proposed resolution
Let’s update our .eslintrc file to add:
"quotes": [2, "single", "avoid-escape"]
Remaining tasks
- Add the new eslint rule.
- Fix the 211 linting errors by switching string from double quotes to single quotes.
- Update Drupal’s JavaScript docs to mention the new recommendation. https://www.drupal.org/node/172169
Quotes
Single quote strings should be used by default. Their use is recommended except in the following case:
Translated strings where one can avoid escaping single quotes by enclosing the string in double quotes. One such string would be
Drupal.t("She's a good person.")
It would beDrupal.t('She's a good person.')
with single quotes. Such escaping may not be handled properly by .pot file generators for text translation, and it’s also somewhat awkward to read.
Tag1 supports the Drupal Project.
To use, we need to install it first. It can be installed locally (per project) or globally. To install it globally:
We can verify that package is installed:
$ npm -g list | grep eslint
├─┬ eslint@7.4.0
│ ├─┬ eslint-scope@5.1.0
│ ├─┬ eslint-utils@2.1.0
│ │ └── eslint-visitor-keys@1.3.0 deduped
│ ├── eslint-visitor-keys@1.3.0
│ │ └── eslint-visitor-keys@1.3.0 deduped
…and also check its command line args:
$ eslint —help
eslint [options] file.js [file.js] [dir]
Basic configuration:
—no-eslintrc Disable use of configuration from .eslintrc.*
-c, —config path::String Use this configuration, overriding .eslintrc.* config options if present
—env [String] Specify environments
—ext [String] Specify JavaScript file extensions
—global [String] Define global variables
—parser String Specify the parser to be used
—parser-options Object Specify parser options
—resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default
Specifying rules and plugins:
—rulesdir [path::String] Use additional rules from this directory
—plugin [String] Specify plugins
—rule Object Specify rules
Fixing problems:
—fix Automatically fix problems
—fix-dry-run Automatically fix problems without saving the changes to the file system
—fix-type Array Specify the types of fixes to apply (problem, suggestion, layout)
Ignoring files:
—ignore-path path::String Specify path of ignore file
—no-ignore Disable use of ignore files and patterns
—ignore-pattern [String] Pattern of files to ignore (in addition to those in .eslintignore)
Using stdin:
—stdin Lint code provided on <STDIN> — default: false
—stdin-filename String Specify filename to process STDIN as
Handling warnings:
—quiet Report errors only — default: false
—max-warnings Int Number of warnings to trigger nonzero exit code — default: -1
Output:
-o, —output-file path::String Specify file to write report to
-f, —format String Use a specific output format — default: stylish
—color, —no-color Force enabling/disabling of color
Inline configuration comments:
—no-inline-config Prevent comments from changing config or rules
—report-unused-disable-directives Adds reported errors for unused eslint-disable directives
Caching:
—cache Only check changed files — default: false
—cache-file path::String Path to the cache file. Deprecated: use —cache-location — default: .eslintcache
—cache-location path::String Path to the cache file or directory
Miscellaneous:
—init Run config initialization wizard — default: false
—env-info Output execution environment information — default: false
—no-error-on-unmatched-pattern Prevent errors when pattern is unmatched
—debug Output debugging information
-h, —help Show help
-v, —version Output the version number
—print-config path::String Print the configuration for the given file
To initialise and configure ESLint launch configuration wizard:
$ eslint —init
ESLint configuration will be saved in file .eslintrc.json (if you opt json file to be used). Example content:
.eslintrc.json:
{
«env»: {
«browser»: true,
«es2020»: true
},
«extends»: «eslint:recommended»,
«parserOptions»: {
«ecmaVersion»: 11
},
«rules»: {
«indent»: [
«error»,
4
],
«quotes»: [
«error»,
«single»
],
«semi»: [
«error»,
«always»
]
}
}
If you use VS Code, you can install ESLint plugin which will pick up this configuration and automatically lint your code and show warnings and error son the go.
ESLint should be added to Node project as a dev dependency.
package.json (created by $npm init):
«devDependencies»: {
«eslint»: «^7.4.0»
}
It is also possible to run this linter from the terminal. For example, to lint all files in the current project recursively with respect to .eslintrc.json:
$eslint .
…
2:32009 error Strings must use singlequote quotes
3:23 error Strings must use singlequote quotes
3:42 error Missing semicolon semi
3:43 error Strings must use singlequote quotes
3:70 error Strings must use singlequote quotes
3:166 error Strings must use singlequote quotes
3:207 error Strings must use singlequote quotes
3:280 error Strings must use singlequote quotes
3:338 error Missing semicolon semi
3:460 error Missing semicolon semi
3:555 error Missing semicolon semi
…
4:22578 error Missing semicolon semi
4:22601 error Missing semicolon semi
✖ 11436 problems (11436 errors, 0 warnings)
To ignore rules in .eslintrc.json and run the linter only for JavaScript files and only to check one particular rule:
/my-project$ eslint . —ext .js —no-eslintrc —rule ‘indent: [«error», 4, { «SwitchCase»: 1 }]’
/my-project/path/to/file.js
28:1 error Expected indentation of 12 spaces but found 16 indent
46:1 error Expected indentation of 12 spaces but found 16 indent
186:1 error Expected indentation of 4 spaces but found 8 indent
187:1 error Expected indentation of 4 spaces but found 8 indent
188:1 error Expected indentation of 4 spaces but found 8 indent
189:1 error Expected indentation of 4 spaces but found 8 indent
Rules used here was indent.