I have ESlint configured with vscode using the plugin, now I’m wondering is there some way I can stop ESlint from showing me the parser/syntax errors, so I can instead view the syntax errors that the Salsa language service provides by default.
Flip
5,9217 gold badges41 silver badges72 bronze badges
asked Mar 11, 2016 at 11:25
The old:
"eslint.enable": false
Is deprecated, now you need to use the builtin VSCode mechanism for disabling extensions:

answered Dec 12, 2020 at 18:46
melMassmelMass
3,2141 gold badge29 silver badges29 bronze badges
In order to disable ESLint only for a specific repo (instead of disabling it globally). Create .vscode folder in your project root and there create a settings.json then add the following config:
{
"eslint.enable": false
}
Maybe after this setting you should consider adding the .vscode/settings.json line to your .gitignore file too, but it is based on your dev team’s preference.
}
Additionally if you’d like to ignore only some vendor/3PP .js files only then you should consider creating an .eslintignore file. Read more about this here.
answered Mar 8, 2019 at 13:05
webpreneurwebpreneur
7559 silver badges15 bronze badges
2
go to File => Preferences => Settings

go to Extensions=>ESLint

Uncheck the EsLint:Enable

answered Oct 24, 2018 at 11:45
1-) npm install -g eslint
2-) Open up settings.json and add the property: "eslint.enable": false
answered Oct 24, 2018 at 9:12
![]()
In VSCode, go to
File >> preferences >> settings
Type ‘eslint quiet’ in the search bar and click
the check box for quiet mode.
In quiet mode, eslint would ignore basic errors.
This should work for many VSCode users as at March 4, 2022.
You’re welcome!
answered Mar 4, 2022 at 17:33
Emeka OrjiEmeka Orji
1583 silver badges10 bronze badges
1
Please open settings.json file and edit the configuration as below:
"eslint.enable": false
Hope this helps.
answered Sep 21, 2022 at 16:23
![]()
1
Disable/uninstall eslint didn’t work for me. I was mistaken thinking only eslint is responsible for linting .ts/.js files.
This VSCode settings worked for me:
{
"typescript.validate.enable": false,
"javascript.validate.enable": false
}
I did it only to check if eslint is responsible for all linting errors. Those settings will not disable eslint linting.
answered Jan 5 at 0:10
![]()
Konrad GrzybKonrad Grzyb
1,19313 silver badges12 bronze badges
ESLint — очень удобный инструмент контроля стиля кода. Но иногда, его нужно отключить. В этой заметке, я расскажу как это сделать.
Общий случай
Для примера, представим, что ESLint ругается у нас в файле есть console.log().
Чтобы временно отключить ESLint, нужно добавить комментарий /* eslint-disable */ перед строками, которые мы хотим проигнорировать:
/* eslint-disable */
console.log('JavaScript debug log');
console.log('eslint is disabled now');
ESLint отключится, как только увидит такой комментарий и не будет анализировать все что идет после него.
Чтобы включить ESLint обратно, используется комментарий /* eslint-enable */.
/* eslint-disable */
console.log('JavaScript debug log');
console.log('eslint is disabled now');
/* eslint-enable */
Чтобы отключить не все правила, а только какие-то определенные, нужно перечислить их в тех же комментариях через запятую:
/* eslint-disable no-console, no-control-regex*/
console.log('JavaScript debug log');
console.log('eslint is disabled now');
Правила eslint-disable и eslint-enable должны всегда находится в блочных комментариях. Так работать не будет:
// eslint-disable no-console, no-control-regex
console.log('JavaScript debug log');
console.log('eslint is disabled now');
Одна строка
Чтобы отключить ESLint для одной строки, можно использовать для варианта.
Для текущей строки — строчный комментарий после окончания строки:
console.log('eslint is disabled for the current line'); // eslint-disable-line
Для следующей строки — строчный комментарий выше строки которую мы отключаем:
// eslint-disable-next-line
console.log('eslint is disabled for the current line');
Весь файл или папка
Чтобы отключить ESLint во всем файле, можно добавить /* eslint-disable */ в первой строке этого файла.
Альтернативно, можно создать файл .eslintignore в корневой директории проекта. Формат этого файла совпадает с форматом .gitignore и ты можешь добавить туда не только файлы, но и папки.
build/*.js
config/*.js
bower_components/foo/*.js
Поскольку JavaScript — это интерпретируемый язык, ошибки, допущенные в коде, выявляются во время его выполнения. Чтобы увидеть ошибки до запуска кода, используется инструмент, который называется линтер. Для поиска ошибок применяется статический анализ и используются особые правила.
Помогаем

Что такое ESLint
ESLint — это инструмент для поиска и исправления ошибок в коде JavaScript и ECMAScript. Он находит синтаксические ошибки, проблемы в шаблонах проектирования и отклонения от стиля. Наряду с большим количеством встроенных правил в нем можно использовать собственные правила или готовые плагины с правилами. Благодаря модульной структуре и множеству возможностей настройки можно настроить ESLint именно так, как нужно для вашего проекта.
Как работать с ESLint: шаг за шагом
Перед установкой ESLint нужно установить Node.js с поддержкой SSL и npm. Предположим, что вы уже сделали это заранее.
Для начала создайте каталог для проекта и поместите в него файл index.js с таким содержимым:
let i = 0;
do {
alert( i );
i++;
} while (true);
Затем инициализируйте npm в этом каталоге, если еще этого не сделали:
Ставайте досвідченим фахівцем з фінансів на рівні директора!
РЕЄСТРУЙТЕСЯ!

npm init
В результате будет создан файл package.json с параметрами пакета.
Установите ESLint в каталоге проекта. Для этого запустите в терминале следующую команду:
npm install eslint --save-dev
ESLint будет установлен локально. Существует возможность глобальной установки (с помощью команды npm install eslint --global), но не рекомендуем использовать такой подход. Все модули и совместно используемые файлы конфигурации в любом случае следует устанавливать локально.
Для настройки файла конфигурации выполните следующую команду:
npx eslint --init
Во время выполнения этой команды вам понадобится ответить на несколько вопросов. Предположим, что нам нужно проверять синтаксис, находить проблемы и применять стиль кодирования:

Обозначения, зачем мы используем ESLint
Укажем, что будут использованы модули JavaScript:

Использование модулей JavaScript
В примере мы не используем ни React, ни Vue.js, ни TypeScript:

Отмечаем, что не используем React и Vue.js
![]()
Отмечаем, что не используем TypeScript
Предположим, код будет выполняться в браузере:
![]()
Указываем, что код будет выполняться в браузере
Укажем, что будем применять инструкции по стилю и выберем Airbnb:

Указываем, что хотим использовать инструкцию по популярным стилям

Для примера выбираем Airbnb
Пусть файл конфигурации будет создан в формате JSON:

Выбираем JSON
Установим зависимости:

Устанавливаем зависимости
В результате в каталоге проекта будет создан файл .eslintrc.json (или с другим расширением — в зависимости от выбранного вами формата).
В нем будет находиться примерно такой код:
module.exports = {
'env': {
'browser': true,
'es2021': true
},
'extends': 'eslint:recommended',
'parserOptions': {
'ecmaVersion': 12,
'sourceType': 'module'
},
'rules': {
}
};
Проверяем проект
Теперь можно проверить проект, вызвав линтер для какого-либо файла или каталога. Вызовем eslint, передав в качестве аргумента текущий каталог (обозначенный точкой): node_modules.bineslint .
В результате получим:

На консоли — четыре ошибки и два предупреждения
Мы видим четыре ошибки и два предупреждения с указанием их позиций в файле. Также в таблице приведены описания и указаны нарушенные правила.
В сообщении указано, что три ошибки можно исправить, указав опцию --fix. Давайте так и сделаем: введем ту же команду и укажем эту опцию:
node_modules.bineslint . --fix
Вывод будет таким:

Три ошибки исправлены
Видим, что линтер сам справился с тремя ошибками, а нам оставил остальные. Код в файле изменен:
let i = 0;
do {
alert(i);
i++;
} while (true);
Обратите внимание: вставлен символ новой строки и убраны пробелы в скобках.
Rules: правила проверки кода
В конфигурации примера выше мы использовали имеющиеся правила проверки. Но можно добавить и свои правила. В файле .eslintrc.json есть раздел rules.
Если при создании проекта указать не имеющийся набор инструкций, а задать свои правила (выбрав пункт Answer questins about your style), то в разделе правил в файле .eslintrc.json можно будет увидеть примерно такие правила:
'rules': {
'indent': [
'error',
4
],
'linebreak-style': [
'error',
'unix'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
]
}
Структура правила проста. Рассмотрим первое правило из приведенного выше примера.
Слово indent — это имя правила. Первый элемент в списке обозначает уровень ошибки и может принимать следующие значения:
offили 0 — выключить правило;warnили 1 — включить правило как предупреждение (не влияет на код выхода);errorили 2 — включить правило как ошибку (с кодом выхода 1).
Второй элемент в этом случае означает количество пробелов. Второй аргумент зависит от правила.
Итак, приведенные выше правила указывают, что следует использовать отступ в четыре пробела, завершение строк в стиле UNIX, одинарные кавычки и не пропускать точку с запятой.
Правила делятся на несколько категорий. Существуют правила проверки на наличие возможных синтаксических и логических ошибок в коде:
getter-return(обязательное применение оператора возврата в методах чтения);-
no-setter-return(запрет применения оператора возврата в методах изменения значения); -
no-dupe-args(запрет дублирующихся аргументов в определениях функций).
Есть правила проверки соблюдения передовой практики, например, accessor-pairs (обязательное применение пар методов чтения и изменения значений в объектах и классах).
Правила относительно переменных (no-unused-vars — запрет на неиспользуемые переменные), стилистические правила (eol-last — разрешение или запрет символа новой строки в конце файла) и правила для ECMAScript 6.
Вернемся к коду, немного изменим файл index.js и отправим его на проверку:
let i = 0
do {
alert("Loop " + i);
i++;
} while (true);
Будут выданы такие сообщения об ошибках:

Сообщения об ошибках
Здесь сообщается, что пропущена точка с запятой, используется отступ в два пробела вместо четырех и двойные кавычки вместо одинарных, а в цикле использовано константное условие.
Полный список правил ESLint можно просмотреть по этой ссылке.
Чтобы не вводить одни и те же команды каждый раз, можно в разделе scripts в файле package.json указать сценарий для запуска eslint. Он может выглядеть так:
"scripts": {
"lint": "eslint . --fix"
},
Вывод будет примерно таким:

Получим такие сообщения об ошибках
Эти сообщения об ошибках можно проигнорировать.
Проверку можно отключать как для отдельных строк, так и для нескольких.
Для отключения отдельной строки ее нужно завершить комментарием:
// eslint-disable-line
Чтобы отключить проверку для нескольких строк, перед ними следует вставить комментарий /* eslint-disable */, а после — /* eslint-enable */:
let i = 0;
do {
alert('Loop ' + i);
i++;
/* eslint-disable */
} while (true);
/* eslint-enable */
Также можно отключить одно или несколько конкретных правил. Для этого в комментарии /* eslint-disable */ их перечисляют через запятую:
/* eslint-disable semi, quotes */
Заключение
ESLint — эффективный инструмент, который можно настраивать и расширять в соответствии с потребностями разных проектов.
ESLint продолжает активно развиваться и интегрируется с Sublime Text 3, Vim, Visual Studio Code, IntelliJ IDEA, Emacs, Eclipse и многими другими средами разработки.
Он играет важную роль, поскольку его обширные возможности дают разработчикам возможность сконцентрировать усилия на разработке, а не на поиске ошибок и несоответствий стилю.
Fixing problems
--fix
Эта опция инструктирует ESLint попытаться исправить как можно больше проблем.Исправления делаются в самих файлах,и выводятся только оставшиеся неисправленные проблемы.Не все проблемы можно исправить с помощью этой опции,и эта опция не работает в таких ситуациях:
- Эта опция вызывает ошибку,когда код передается в ESLint.
- Эта опция не влияет на код,использующий процессор,если только процессор не разрешает автоисправление.
Если вы хотите исправить код из стандартного stdin или иным образом хотите получить исправления, не записывая их в файл, используйте параметр --fix-dry-run .
--fix-dry-run
Этот параметр имеет тот же эффект, что и --fix , с одним отличием: исправления не сохраняются в файловой системе. Это позволяет исправить код из stdin (при использовании с флагом --stdin ).
Поскольку форматер по умолчанию не выводит фиксированный код, вам придется использовать другой (например , json ), чтобы получить исправления. Вот пример этого шаблона:
getSomeText | npx eslint
Этот флаг может быть полезен для интеграции (например,для плагинов редактора),которые должны автоматически исправлять текст из командной строки,не сохраняя его в файловую систему.
--fix-type
Этот параметр позволяет указать тип исправлений, которые следует применять при использовании --fix или --fix-dry-run . Есть четыре типа исправлений:
-
problem— исправить возможные ошибки в коде -
suggestion— применить исправления к коду, которые улучшают его -
layout— применить исправления, не меняющие структуру программы (AST) -
directive— применить исправления к встроенным директивам, таким как// eslint-disable
В командной строке можно указать один или несколько типов исправлений.Приведем несколько примеров:
npx eslint --fix --fix-type suggestion .npx eslint --fix --fix-type suggestion --fix-type problem .npx eslint --fix --fix-type suggestion,layout .
Этот вариант полезен,если вы используете другую программу для форматирования вашего кода,но все равно хотите,чтобы ESLint применял другие типы исправлений.
Ignoring files
--ignore-path
Эта опция позволяет вам указать файл, который будет использоваться в качестве вашего .eslintignore . По умолчанию ESLint выглядит в текущем рабочем каталоге для .eslintignore . Вы можете изменить это поведение, указав путь к другому файлу.
Example:
npx eslint --ignore-path tmp/.eslintignore file.jsnpx eslint --ignore-path .gitignore file.js
--no-ignore
Отключает исключение файлов из .eslintignore , --ignore-path , --ignore-pattern и ignorePatterns в файлах конфигурации.
Example:
npx eslint --no-ignore file.js
--ignore-pattern
Этот параметр позволяет указать шаблоны файлов, которые следует игнорировать (в дополнение к файлам в .eslintignore ). Вы можете повторить опцию, чтобы предоставить несколько шаблонов. Поддерживаемый синтаксис такой же, как и для файлов .eslintignore , которые используют те же шаблоны, что и спецификация .gitignore . Вы должны цитировать свои шаблоны, чтобы избежать интерпретации шаблонов глобусов оболочкой. .gitignore
Example:
npx eslint --ignore-pattern '/lib/' --ignore-pattern '/src/vendor/*' .
Using stdin
--stdin
Эта опция говорит ESLint читать и подшивать исходный код из STDIN,а не из файлов.Вы можете использовать это для переноса кода в ESLint.
Example:
cat myfile.js | npx eslint --stdin
--stdin-filename
Эта опция позволяет указать имя файла для обработки STDIN как.Это полезно при обработке файлов из STDIN,и у вас есть правила,которые зависят от имени файла.
Example
cat myfile.js | npx eslint --stdin --stdin-filename=myfile.js
Handling warnings
--quiet
Эта опция позволяет отключить отправку отчетов по предупреждениям.Если вы включите эту опцию,то ESLint будет сообщать только об ошибках.
Example:
npx eslint --quiet file.js
--max-warnings
Эта опция позволяет указать порог предупреждения,который может быть использован для принуждения ESLint к выходу со статусом ошибки,если в вашем проекте слишком много нарушений правил на уровне предупреждений.
Обычно, если ESLint запускается и не находит ошибок (только предупреждения), он завершается с успешным статусом выхода. Однако, если --max-warnings и общее количество предупреждений превышает указанный порог, ESLint выйдет со статусом ошибки. Указание порога -1 или пропуск этой опции предотвратит такое поведение.
Example:
npx eslint --max-warnings 10 file.js
Output
-o, --output-file
Включите запись отчета в файл.
Example:
npx eslint -o ./test/test.html
При указании данный формат выводится в указанное имя файла.
-f, --format
Эта опция задает выходной формат консоли.Возможные форматы:
- checkstyle
- compact
- html
- jslint-xml
- json
- junit
- стильный (по умолчанию)
- tap
- unix
- visualstudio
Example:
npx eslint -f compact file.js
Вы также можете использовать пользовательскую батарею из командной строки,указав путь к файлу пользовательской батареи.
Example:
npx eslint -f ./customformat.js file.js
Установленный npm форматтер разрешается с eslint-formatter- или без него .
Example:
npm install eslint-formatter-prettynpx eslint -f pretty file.js
При указании заданного формата выводятся данные в консоль.Если вы хотите сохранить этот вывод в файл,вы можете сделать это в командной строке следующим образом:
npx eslint -f compact file.js > results.txt
Результат будет сохранен в файле results.txt .
--color, --no-color
Эта опция принудительно включает / выключает цветной вывод. Вы можете использовать это, чтобы переопределить поведение по умолчанию, которое состоит в том, чтобы включить цветной вывод, если не обнаружен TTY, например, при eslint через cat или less .
Examples:
npx eslint
--no-inline-config
Этот параметр предотвращает любые действия встроенных комментариев, таких как /*eslint-disable*/ или /*global foo*/ . Это позволяет вам установить конфигурацию ESLint без изменения файлов. Все встроенные комментарии к конфигурации игнорируются, например:
/*eslint-disable*//*eslint-enable*//*global*//*eslint*//*eslint-env*/// eslint-disable-line// eslint-disable-next-line
Example:
npx eslint --no-inline-config file.js
--report-unused-disable-directives
Эта опция заставляет ESLint сообщать о комментариях директивы, таких как // eslint-disable-line если в этой строке в любом случае не было бы сообщений об ошибках. Это может быть полезно для предотвращения непредвиденного подавления будущих ошибок путем очистки старых комментариев eslint-disable , которые больше не применимы.
Предупреждение : при использовании этой опции возможно, что новые ошибки начнут сообщаться при обновлении ESLint или пользовательских правил. Например, предположим, что в правиле есть ошибка, из-за которой оно сообщает о ложном срабатывании, и eslint-disable комментарий eslint-disable для подавления неверного отчета. Если ошибка затем будет исправлена в выпуске патча ESLint, комментарий eslint-disable перестанет использоваться, поскольку ESLint больше не генерирует неверный отчет. Это приведет к новому сообщению об ошибке для неиспользуемой директивы, если report-unused-disable-directives опция report-unused-disable-directives .
Example:
npx eslint --report-unused-disable-directives file.js
Caching
--cache
Храните информацию об обработанных файлах, чтобы работать только с измененными. Кэш по умолчанию хранится в .eslintcache . Включение этой опции может значительно улучшить время работы ESLint, гарантируя, что будут проверены только измененные файлы.
Примечание. Если вы запустите ESLint с --cache , а затем запустите ESLint без --cache , файл .eslintcache будет удален. Это необходимо, поскольку результаты lint могут измениться и сделать .eslintcache недействительным. Если вы хотите контролировать, когда файл кеша удаляется, используйте --cache-location , чтобы указать альтернативное расположение для файла кеша.
Примечание. Файлы с автофиксацией не помещаются в кеш. Последующий линтинг, который не запускает автоисправление, поместит его в кеш.
--cache-file
Путь к файлу кеша. Если не указан .eslintcache будет использоваться. Файл будет создан в каталоге, где eslint команда eslint . Не рекомендуется : используйте вместо этого --cache-location .
--cache-location
Путь к расположению кеша. Может быть файлом или каталогом. Если местоположение не указано, будет использоваться .eslintcache . В этом случае файл будет создан в каталоге, в котором eslint команда eslint .
Если указан каталог, в указанной папке будет создан файл кеша. Имя файла будет основано на хеш-коде текущего рабочего каталога (CWD). например: .cache_hashOfCWD
Важное примечание: если каталог для кеша не существует, убедитесь, что вы добавили конечный / on * nix systems или in windows. В противном случае путь будет считаться файлом.
Example:
npx eslint "src*.js" --cache --cache-location "/Users/user/.eslintcache/"
--cache-strategy
Стратегия использования кеша для обнаружения измененных файлов. Могут быть либо metadata либо content . Если стратегия не указана, будут использоваться metadata .
content стратегия может быть полезна в тех случаях , когда время модификации файлов изменится , даже если их содержание нет. Например, это может произойти во время операций git, таких как git clone, потому что git не отслеживает время изменения файла.
Example:
npx eslint "src*.js" --cache --cache-strategy content
Miscellaneous
--init
Эта опция запустит npm init @eslint/config , чтобы запустить мастер инициализации конфигурации. Он разработан, чтобы помочь новым пользователям быстро создать файл .eslintrc, ответив на несколько вопросов, выбрав популярное руководство по стилю.
Полученный конфигурационный файл будет создан в текущем каталоге.
--env-info
Эта опция выводит информацию о среде исполнения,включая версию Node,npm,а также локальные и глобальные установки ESLint.Команда ESLint может запросить эту информацию,чтобы помочь в решении ошибок.
--no-error-on-unmatched-pattern
Эта опция предотвращает ошибки, когда шаблон глобуса в кавычках или --ext не имеет соответствия. Это не предотвратит ошибки, когда ваша оболочка не может сопоставить глобус.
--exit-on-fatal-error
Эта опция заставляет ESLint завершать работу с кодом выхода 2,если произошла одна или несколько фатальных ошибок синтаксического анализа.Без этой опции фатальные ошибки синтаксического анализа сообщаются как нарушения правил.
--debug
Эта опция выводит отладочную информацию на консоль. Эта информация полезна, когда вы видите проблему и вам трудно ее точно определить. Команда ESLint может запросить эту отладочную информацию, чтобы помочь устранить ошибки. Добавьте этот флаг в вызов командной строки ESLint, чтобы получить дополнительную отладочную информацию при выполнении команды (например npx eslint --debug test.js и npx eslint test.js --debug эквивалентны)
-h, --help
Эта опция выводит меню помощи,отображая все доступные опции.Все остальные опции при их наличии игнорируются.
-v, --version
Эта опция выводит текущую версию ESLint на консоль.Все остальные опции при их наличии игнорируются.
--print-config
Эта опция выводит конфигурацию,которая будет использоваться для передаваемого файла.В настоящее время не выполняется подкатка и действительны только опции,связанные с конфигурацией.
Example:
npx eslint --print-config file.js
Игнорирование файлов из подшивки
ESLint поддерживает файлы .eslintignore для исключения файлов из процесса линтинга, когда ESLint работает с каталогом. Файлы, указанные как отдельные аргументы CLI, не будут исключены. Файл .eslintignore представляет собой обычный текстовый файл, содержащий по одному шаблону в строке. Он может находиться в любом из предков целевого каталога; это повлияет на файлы в содержащем его каталоге, а также на все подкаталоги. Вот простой пример файла .eslintignore :
temp.js**/vendor/*.js
Более подробную разбивку поддерживаемых шаблонов и каталогов, которые ESLint игнорирует по умолчанию, можно найти в Ignoring Code .
Exit codes
При перетаскивании файлов ESLint выходит с одним из следующих кодов выхода:
-
0: Линтинг прошел успешно, ошибок линтинга нет. Если флаг--max-warningsустановлен вn, количество предупреждений о линтинге не превышаетn. -
1: Линтинг прошел успешно, и есть хотя бы одна ошибка линтинга, или имеется больше предупреждений линтинга, чем разрешено параметром--max-warnings. -
2: Линтинг не удался из-за проблемы конфигурации или внутренней ошибки.
© OpenJS Foundation and other contributors
Licensed under the MIT License.
https://eslint.org/docs/latest/user-guide/command-line-interface
ESLint
8.30
- yoda
- Требовать или запрещать условия «Йода» Некоторые проблемы, о которых сообщает это правило, автоматически устраняются с помощью параметра командной строки. Условия Йоды названы так.
- Интерфейс командной строки
- Для установки ESLint требуется Node.js.
- Configuration Files
- ESLint supports configuration files several formats: If there are multiple configuration files in same directory, ESLint will only use one.
- Using a configuration from a plugin
- A plugin is an npm package that can add various extensions to ESLint.
ESLint is designed to be completely configurable, meaning you can turn off every rule and run only with basic syntax validation, or mix and match the bundled rules and your custom rules to make ESLint perfect for your project. There are two primary ways to configure ESLint:
- Configuration Comments — use JavaScript comments to embed configuration information directly into a file.
- Configuration Files — use a JavaScript, JSON or YAML file to specify configuration information for an entire directory and all of its subdirectories. This can be in the form of an .eslintrc.* file or an
eslintConfigfield in apackage.jsonfile, both of which ESLint will look for and read automatically, or you can specify a configuration file on the command line.
There are several pieces of information that can be configured:
- Environments — which environments your script is designed to run in. Each environment brings with it a certain set of predefined global variables.
- Globals — the additional global variables your script accesses during execution.
- Rules — which rules are enabled and at what error level.
All of these options give you fine-grained control over how ESLint treats your code.
Specifying Parser Options
ESLint allows you to specify the JavaScript language options you want to support. By default, ESLint expects ECMAScript 5 syntax. You can override that setting to enable support for other ECMAScript versions as well as JSX by using parser options.
Please note that supporting JSX syntax is not the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn’t recognize. We recommend using eslint-plugin-react if you are using React and want React semantics.
By the same token, supporting ES6 syntax is not the same as supporting new ES6 globals (e.g., new types such as
Set).
For ES6 syntax, use { "parserOptions": { "ecmaVersion": 6 } }; for new ES6 global variables, use { "env": (this setting enables ES6 syntax automatically).
{ "es6": true } }
Parser options are set in your .eslintrc.* file by using the parserOptions property. The available options are:
ecmaVersion— set to 3, 5 (default), 6, 7, or 8 to specify the version of ECMAScript syntax you want to use. You can also set to 2015 (same as 6), 2016 (same as 7), or 2017 (same as 8) to use the year-based naming.sourceType— set to"script"(default) or"module"if your code is in ECMAScript modules.ecmaFeatures— an object indicating which additional language features you’d like to use:globalReturn— allowreturnstatements in the global scopeimpliedStrict— enable global strict mode (ifecmaVersionis 5 or greater)jsx— enable JSXexperimentalObjectRestSpread— enable support for the experimental object rest/spread properties (IMPORTANT: This is an experimental feature that may change significantly in the future. It’s recommended that you do not write rules relying on this functionality unless you are willing to incur maintenance cost when it changes.)
Here’s an example .eslintrc.json file:
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"semi": 2
}
}
Setting parser options helps ESLint determine what is a parsing error. All language options are false by default.
Specifying Parser
By default, ESLint uses Espree as its parser. You can optionally specify that a different parser should be used in your configuration file so long as the parser meets the following requirements:
- It must be an npm module installed locally.
- It must have an Esprima-compatible interface (it must export a
parse()method). - It must produce Esprima-compatible AST and token objects.
Note that even with these compatibilities, there are no guarantees that an external parser will work correctly with ESLint and ESLint will not fix bugs related to incompatibilities with other parsers.
To indicate the npm module to use as your parser, specify it using the parser option in your .eslintrc file. For example, the following specifies to use Esprima instead of Espree:
{
"parser": "esprima",
"rules": {
"semi": "error"
}
}
The following parsers are compatible with ESLint:
- Esprima
- Babel-ESLint — A wrapper around the Babel parser that makes it compatible with ESLint.
- typescript-eslint-parser(Experimental) — A parser that converts TypeScript into an ESTree-compatible form so it can be used in ESLint. The goal is to allow TypeScript files to be parsed by ESLint (though not necessarily pass all ESLint rules).
Note when using a custom parser, the parserOptions configuration property is still required for ESLint to work properly with features not in ECMAScript 5 by default. Parsers are all passed parserOptions and may or may not use them to determine which features to enable.
Specifying Environments
An environment defines global variables that are predefined. The available environments are:
browser— browser global variables.node— Node.js global variables and Node.js scoping.commonjs— CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).shared-node-browser— Globals common to both Node and Browser.es6— enable all ECMAScript 6 features except for modules (this automatically sets theecmaVersionparser option to 6).worker— web workers global variables.amd— definesrequire()anddefine()as global variables as per the amd spec.mocha— adds all of the Mocha testing global variables.jasmine— adds all of the Jasmine testing global variables for version 1.3 and 2.0.jest— Jest global variables.phantomjs— PhantomJS global variables.protractor— Protractor global variables.qunit— QUnit global variables.jquery— jQuery global variables.prototypejs— Prototype.js global variables.shelljs— ShellJS global variables.meteor— Meteor global variables.mongo— MongoDB global variables.applescript— AppleScript global variables.nashorn— Java 8 Nashorn global variables.serviceworker— Service Worker global variables.atomtest— Atom test helper globals.embertest— Ember test helper globals.webextensions— WebExtensions globals.greasemonkey— GreaseMonkey globals.
These environments are not mutually exclusive, so you can define more than one at a time.
Environments can be specified inside of a file, in configuration files or using the --env command line flag.
To specify environments using a comment inside of your JavaScript file, use the following format:
/* eslint-env node, mocha */
This enables Node.js and Mocha environments.
To specify environments in a configuration file, use the env key and specify which environments you want to enable by setting each to true. For example, the following enables the browser and Node.js environments:
{
"env": {
"browser": true,
"node": true
}
}
Or in a package.json file
{
"name": "mypackage",
"version": "0.0.1",
"eslintConfig": {
"env": {
"browser": true,
"node": true
}
}
}
And in YAML:
---
env:
browser: true
node: true
If you want to use an environment from a plugin, be sure to specify the plugin name in the plugins array and then use the unprefixed plugin name, followed by a slash, followed by the environment name. For example:
{
"plugins": ["example"],
"env": {
"example/custom": true
}
}
Or in a package.json file
{
"name": "mypackage",
"version": "0.0.1",
"eslintConfig": {
"plugins": ["example"],
"env": {
"example/custom": true
}
}
}
And in YAML:
---
plugins:
- example
env:
example/custom: true
Specifying Globals
The no-undef rule will warn on variables that are accessed but not defined within the same file. If you are using global variables inside of a file then it’s worthwhile to define those globals so that ESLint will not warn about their usage. You can define global variables either using comments inside of a file or in the configuration file.
To specify globals using a comment inside of your JavaScript file, use the following format:
This defines two global variables, var1 and var2. If you want to optionally specify that these global variables should never be written to (only read), then you can set each with a false flag:
/* global var1:false, var2:false */
To configure global variables inside of a configuration file, use the globals key and indicate the global variables you want to use. Set each global variable name equal to true to allow the variable to be overwritten or false to disallow overwriting. For example:
{
"globals": {
"var1": true,
"var2": false
}
}
And in YAML:
---
globals:
var1: true
var2: false
These examples allow var1 to be overwritten in your code, but disallow it for var2.
Note: Enable the no-global-assign rule to disallow modifications to read-only global variables in your code.
Configuring Plugins
ESLint supports the use of third-party plugins. Before using the plugin you have to install it using npm.
To configure plugins inside of a configuration file, use the plugins key, which contains a list of plugin names. The eslint-plugin- prefix can be omitted from the plugin name.
{
"plugins": [
"plugin1",
"eslint-plugin-plugin2"
]
}
And in YAML:
---
plugins:
- plugin1
- eslint-plugin-plugin2
Note: A globally-installed instance of ESLint can only use globally-installed ESLint plugins. A locally-installed ESLint can make use of both locally- and globally- installed ESLint plugins.
Configuring Rules
ESLint comes with a large number of rules. You can modify which rules your project uses either using configuration comments or configuration files. To change a rule setting, you must set the rule ID equal to one of these values:
"off"or0— turn the rule off"warn"or1— turn the rule on as a warning (doesn’t affect exit code)"error"or2— turn the rule on as an error (exit code is 1 when triggered)
To configure rules inside of a file using configuration comments, use a comment in the following format:
/* eslint eqeqeq: "off", curly: "error" */
In this example, eqeqeq is turned off and curly is turned on as an error. You can also use the numeric equivalent for the rule severity:
/* eslint eqeqeq: 0, curly: 2 */
This example is the same as the last example, only it uses the numeric codes instead of the string values. The eqeqeq rule is off and the curly rule is set to be an error.
If a rule has additional options, you can specify them using array literal syntax, such as:
/* eslint quotes: ["error", "double"], curly: 2 */
This comment specifies the “double” option for the quotes rule. The first item in the array is always the rule severity (number or string).
To configure rules inside of a configuration file, use the rules key along with an error level and any options you want to use. For example:
{
"rules": {
"eqeqeq": "off",
"curly": "error",
"quotes": ["error", "double"]
}
}
And in YAML:
---
rules:
eqeqeq: off
curly: error
quotes:
- error
- double
To configure a rule which is defined within a plugin you have to prefix the rule ID with the plugin name and a /. For example:
{
"plugins": [
"plugin1"
],
"rules": {
"eqeqeq": "off",
"curly": "error",
"quotes": ["error", "double"],
"plugin1/rule1": "error"
}
}
And in YAML:
---
plugins:
- plugin1
rules:
eqeqeq: 0
curly: error
quotes:
- error
- "double"
plugin1/rule1: error
In these configuration files, the rule plugin1/rule1 comes from the plugin named plugin1. You can also use this format with configuration comments, such as:
/* eslint "plugin1/rule1": "error" */
Note: When specifying rules from plugins, make sure to omit eslint-plugin-. ESLint uses only the unprefixed name internally to locate rules.
To temporarily disable rule warnings in your file, use block comments in the following format:
/* eslint-disable */
alert('foo');
/* eslint-enable */
You can also disable or enable warnings for specific rules:
/* eslint-disable no-alert, no-console */
alert('foo');
console.log('bar');
/* eslint-enable no-alert, no-console */
To disable rule warnings in an entire file, put a /* eslint-disable */ block comment at the top of the file:
/* eslint-disable */
alert('foo');
You can also disable or enable specific rules for an entire file:
/* eslint-disable no-alert */
alert('foo');
To disable all rules on a specific line, use a line comment in one of the following formats:
alert('foo'); // eslint-disable-line
// eslint-disable-next-line
alert('foo');
To disable a specific rule on a specific line:
alert('foo'); // eslint-disable-line no-alert
// eslint-disable-next-line no-alert
alert('foo');
To disable multiple rules on a specific line:
alert('foo'); // eslint-disable-line no-alert, quotes, semi
// eslint-disable-next-line no-alert, quotes, semi
alert('foo');
All of the above methods also work for plugin rules. For example, to disable eslint-plugin-example’s rule-name rule, combine the plugin’s name (example) and the rule’s name (rule-name) into example/rule-name:
foo(); // eslint-disable-line example/rule-name
Note: Comments that disable warnings for a portion of a file tell ESLint not to report rule violations for the disabled code. ESLint still parses the entire file, however, so disabled code still needs to be syntactically valid JavaScript.
ESLint supports adding shared settings into configuration file. You can add settings object to ESLint configuration file and it will be supplied to every rule that will be executed. This may be useful if you are adding custom rules and want them to have access to the same information and be easily configurable.
In JSON:
{
"settings": {
"sharedData": "Hello"
}
}
And in YAML:
---
settings:
sharedData: "Hello"
Using Configuration Files
There are two ways to use configuration files. The first is to save the file wherever you would like and pass its location to the CLI using the -c option, such as:
eslint -c myconfig.json myfiletotest.js
The second way to use configuration files is via .eslintrc.* and package.json files. ESLint will automatically look for them in the directory of the file to be linted, and in successive parent directories all the way up to the root directory of the filesystem. This option is useful when you want different configurations for different parts of a project or when you want others to be able to use ESLint directly without needing to remember to pass in the configuration file.
In each case, the settings in the configuration file override default settings.
Configuration File Formats
ESLint supports configuration files in several formats:
- JavaScript — use
.eslintrc.jsand export an object containing your configuration. - YAML — use
.eslintrc.yamlor.eslintrc.ymlto define the configuration structure. - JSON — use
.eslintrc.jsonto define the configuration structure. ESLint’s JSON files also allow JavaScript-style comments. - Deprecated — use
.eslintrc, which can be either JSON or YAML. - package.json — create an
eslintConfigproperty in yourpackage.jsonfile and define your configuration there.
If there are multiple configuration files in the same directory, ESLint will only use one. The priority order is:
.eslintrc.js.eslintrc.yaml.eslintrc.yml.eslintrc.json.eslintrcpackage.json
Configuration Cascading and Hierarchy
When using .eslintrc.* and package.json files for configuration, you can take advantage of configuration cascading. For instance, suppose you have the following structure:
your-project
├── .eslintrc
├── lib
│ └── source.js
└─┬ tests
├── .eslintrc
└── test.js
The configuration cascade works by using the closest .eslintrc file to the file being linted as the highest priority, then any configuration files in the parent directory, and so on. When you run ESLint on this project, all files in lib/ will use the .eslintrc file at the root of the project as their configuration. When ESLint traverses into the tests/ directory, it will then use your-project/tests/.eslintrc in addition to your-project/.eslintrc. So your-project/tests/test.js is linted based on the combination of the two .eslintrc files in its directory hierarchy, with the closest one taking priority. In this way, you can have project-level ESLint settings and also have directory-specific overrides.
In the same way, if there is a package.json file in the root directory with an eslintConfig field, the configuration it describes will apply to all subdirectories beneath it, but the configuration described by the .eslintrc file in the tests directory will override it where there are conflicting specifications.
your-project
├── package.json
├── lib
│ └── source.js
└─┬ tests
├── .eslintrc
└── test.js
If there is an .eslintrc and a package.json file found in the same directory, .eslintrc will take a priority and package.json file will not be used.
Note: If you have a personal configuration file in your home directory (~/.eslintrc), it will only be used if no other configuration files are found. Since a personal configuration would apply to everything inside of a user’s directory, including third-party code, this could cause problems when running ESLint.
By default, ESLint will look for configuration files in all parent folders up to the root directory. This can be useful if you want all of your projects to follow a certain convention, but can sometimes lead to unexpected results. To limit ESLint to a specific project, place "root": true inside the eslintConfig field of the package.json file or in the .eslintrc.* file at your project’s root level. ESLint will stop looking in parent folders once it finds a configuration with "root": true.
And in YAML:
For example, consider projectA which has "root": true set in the .eslintrc file in the lib/ directory. In this case, while linting main.js, the configurations within lib/ will be used, but the .eslintrc file in projectA/ will not.
home
└── user
├── .eslintrc <- Always skipped if other configs present
└── projectA
├── .eslintrc <- Not used
└── lib
├── .eslintrc <- { "root": true }
└── main.js
The complete configuration hierarchy, from highest precedence to lowest precedence, is as follows:
- Inline configuration
/*eslint-disable*/and/*eslint-enable*//*global*//*eslint*//*eslint-env*/
- Command line options:
--global--rule--env-c,--config
- Project-level configuration:
.eslintrc.*orpackage.jsonfile in same directory as linted file- Continue searching for
.eslintrcandpackage.jsonfiles in ancestor directories (parent has highest precedence, then grandparent, etc.), up to and including the root directory or until a config with"root": trueis found. - In the absence of any configuration from (1) thru (3), fall back to a personal default configuration in
~/.eslintrc.
Extending Configuration Files
A configuration file can extend the set of enabled rules from base configurations.
The extends property value is either:
- a string that specifies a configuration
- an array of strings: each additional configuration extends the preceding configurations
ESLint extends configurations recursively so a base configuration can also have an extends property.
The rules property can do any of the following to extend (or override) the set of rules:
- enable additional rules
- change an inherited rule’s severity without changing its options:
- Base config:
"eqeqeq": ["error", "allow-null"] - Derived config:
"eqeqeq": "warn" - Resulting actual config:
"eqeqeq": ["warn", "allow-null"]
- Base config:
- override options for rules from base configurations:
- Base config:
"quotes": ["error", "single", "avoid-escape"] - Derived config:
"quotes": ["error", "single"] - Resulting actual config:
"quotes": ["error", "single"]
- Base config:
Using "eslint:recommended"
An extends property value "eslint:recommended" enables a subset of core rules that report common problems, which have a check mark on the rules page. The recommended subset can change only at major versions of ESLint.
If your configuration extends the recommended rules: after you upgrade to a newer major version of ESLint, review the reported problems before you use the --fix option on the command line, so you know if a new fixable recommended rule will make changes to the code.
The eslint --init command can create a configuration so you can extend the recommended rules.
Example of a configuration file in JavaScript format:
module.exports = {
"extends": "eslint:recommended",
"rules": {
// enable additional rules
"indent": ["error", 4],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "double"],
"semi": ["error", "always"],
// override default options for rules from base configurations
"comma-dangle": ["error", "always"],
"no-cond-assign": ["error", "always"],
// disable rules from base configurations
"no-console": "off",
}
}
Using a shareable configuration package
A sharable configuration is an npm package that exports a configuration object. Make sure the package has been installed to a directory where ESLint can require it.
The extends property value can omit the eslint-config- prefix of the package name.
The eslint --init command can create a configuration so you can extend a popular style guide (for example, eslint-config-standard).
Example of a configuration file in YAML format:
extends: standard
rules:
comma-dangle:
- error
- always
no-empty: warn
Using the configuration from a plugin
A plugin is an npm package that usually exports rules. Some plugins also export one or more named configurations. Make sure the package has been installed to a directory where ESLint can require it.
The plugins property value can omit the eslint-plugin- prefix of the package name.
The extends property value can consist of:
plugin:- the package name (from which you can omit the prefix, for example,
react) /- the configuration name (for example,
recommended)
Example of a configuration file in JSON format:
{
"plugins": [
"react"
],
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"rules": {
"no-set-state": "off"
}
}
Using a configuration file
The extends property value can be an absolute or relative path to a base configuration file.
ESLint resolves a relative path to a base configuration file relative to the configuration file that uses it unless that file is in your home directory or a directory that isn’t an ancestor to the directory in which ESLint is installed (either locally or globally). In those cases, ESLint resolves the relative path to the base file relative to the linted project directory (typically the current working directory).
Example of a configuration file in JSON format:
{
"extends": [
"./node_modules/coding-standard/eslintDefaults.js",
"./node_modules/coding-standard/.eslintrc-es6",
"./node_modules/coding-standard/.eslintrc-jsx"
],
"rules": {
"eqeqeq": "warn"
}
}
Using "eslint:all"
The extends property value can be "eslint:all" to enable all core rules in the currently installed version of ESLint. The set of core rules can change at any minor or major version of ESLint.
Important: This configuration is not recommended for production use because it changes with every minor and major version of ESLint. Use at your own risk.
If you configure ESLint to automatically enable new rules when you upgrade, ESLint can report new problems when there are no changes to source code, therefore any newer minor version of ESLint can behave as if it has breaking changes.
You might enable all core rules as a shortcut to explore rules and options while you decide on the configuration for a project, especially if you rarely override options or disable rules. The default options for rules are not endorsements by ESLint (for example, the default option for the quotes rule does not mean double quotes are better than single quotes).
If your configuration extends all core rules: after you upgrade to a newer major or minor version of ESLint, review the reported problems before you use the --fix option on the command line, so you know if a new fixable rule will make changes to the code.
Example of a configuration file in JavaScript format:
module.exports = {
"extends": "eslint:all",
"rules": {
// override default options
"comma-dangle": ["error", "always"],
"indent": ["error", 2],
"no-cond-assign": ["error", "always"],
// disable now, but enable in the future
"one-var": "off", // ["error", "never"]
// disable
"init-declarations": "off",
"no-console": "off",
"no-inline-comments": "off",
}
}
Configuration Based on Glob Patterns
Sometimes a more fine-controlled configuration is necessary, for example if the configuration for files within the same directory has to be different. Therefore you can provide configurations under the overrides key that will only apply to files that match specific glob patterns, using the same format you would pass on the command line (e.g., app/**/*.test.js).
How it works
- Glob pattern overrides can only be configured within config files (
.eslintrc.*orpackage.json). - The patterns are applied against the file path relative to the directory of the config file. For example, if your config file has the path
/Users/john/workspace/any-project/.eslintrc.jsand the file you want to lint has the path/Users/john/workspace/any-project/lib/util.js, then the pattern provided in.eslintrc.jswill be executed against the relative pathlib/util.js. - Glob pattern overrides have higher precedence than the regular configuration in the same config file. Multiple overrides within the same config are applied in order. That is, the last override block in a config file always has the highest precedence.
- A glob specific configuration works almost the same as any other ESLint config. Override blocks can contain any configuration options that are valid in a regular config, with the exception of
extends,overrides, androot. - Multiple glob patterns can be provided within a single override block. A file must match at least one of the supplied patterns for the configuration to apply.
- Override blocks can also specify patterns to exclude from matches. If a file matches any of the excluded patterns, the configuration won’t apply.
Relative glob patterns
project-root
├── app
│ ├── lib
│ │ ├── foo.js
│ │ ├── fooSpec.js
│ ├── components
│ │ ├── bar.js
│ │ ├── barSpec.js
│ ├── .eslintrc.json
├── server
│ ├── server.js
│ ├── serverSpec.js
├── .eslintrc.json
The config in app/.eslintrc.json defines the glob pattern **/*Spec.js. This pattern is relative to the base directory of app/.eslintrc.json. So, this pattern would match app/lib/fooSpec.js and app/components/barSpec.js but NOT server/serverSpec.js. If you defined the same pattern in the .eslintrc.json file within in the project-root folder, it would match all three of the *Spec files.
Example configuration
In your .eslintrc.json:
{
"rules": {
"quotes": [ 2, "double" ]
},
"overrides": [
{
"files": [ "bin/*.js", "lib/*.js" ],
"excludedFiles": "*.test.js",
"rules": {
"quotes": [ 2, "single" ]
}
}
]
}
Both the JSON and YAML configuration file formats support comments (package.json files should not include them). You can use JavaScript-style comments or YAML-style comments in either type of file and ESLint will safely ignore them. This allows your configuration files to be more human-friendly. For example:
{
"env": {
"browser": true
},
"rules": {
// Override our default settings just for this directory
"eqeqeq": "warn",
"strict": "off"
}
}
Specifying File extensions to Lint
Currently the sole method for telling ESLint which file extensions to lint is by specifying a comma separated list of extensions using the --ext command line option. Note this flag only takes effect in conjunction with directories, and will be ignored if used with filenames or glob patterns.
Ignoring Files and Directories
You can tell ESLint to ignore specific files and directories by creating an .eslintignore file in your project’s root directory. The .eslintignore file is a plain text file where each line is a glob pattern indicating which paths should be omitted from linting. For example, the following will omit all JavaScript files:
When ESLint is run, it looks in the current working directory to find an .eslintignore file before determining which files to lint. If this file is found, then those preferences are applied when traversing directories. Only one .eslintignore file can be used at a time, so .eslintignore files other than the one in the current working directory will not be used.
Globs are matched using node-ignore, so a number of features are available:
- Lines beginning with
#are treated as comments and do not affect ignore patterns. - Paths are relative to
.eslintignorelocation or the current working directory. This also influences paths passed via--ignore-pattern. - Ignore patterns behave according to the
.gitignorespecification - Lines preceded by
!are negated patterns that re-include a pattern that was ignored by an earlier pattern.
In addition to any patterns in a .eslintignore file, ESLint always ignores files in /node_modules/* and /bower_components/*.
For example, placing the following .eslintignore file in the current working directory will ignore all of node_modules, bower_components and anything in the build/ directory except build/index.js:
# /node_modules/* and /bower_components/* ignored by default
# Ignore built files except build/index.js
build/*
!build/index.js
Using an Alternate File
If you’d prefer to use a different file than the .eslintignore in the current working directory, you can specify it on the command line using the --ignore-path option. For example, you can use .jshintignore file because it has the same format:
eslint --ignore-path .jshintignore file.js
You can also use your .gitignore file:
eslint --ignore-path .gitignore file.js
Any file that follows the standard ignore file format can be used. Keep in mind that specifying --ignore-path means that any existing .eslintignore file will not be used. Note that globbing rules in .eslintignore follow those of .gitignore.
Using eslintIgnore in package.json
If an .eslintignore file is not found and an alternate file is not specified, eslint will look in package.json for an eslintIgnore key to check for files to ignore.
{
"name": "mypackage",
"version": "0.0.1",
"eslintConfig": {
"env": {
"browser": true,
"node": true
}
},
"eslintIgnore": ["hello.js", "world.js"]
}
Ignored File Warnings
When you pass directories to ESLint, files and directories are silently ignored. If you pass a specific file to ESLint, then you will see a warning indicating that the file was skipped. For example, suppose you have an .eslintignore file that looks like this:
And then you run:
You’ll see this warning:
foo.js
0:0 warning File ignored because of your .eslintignore file. Use --no-ignore to override.
✖ 1 problem (0 errors, 1 warning)
This message occurs because ESLint is unsure if you wanted to actually lint the file or not. As the message indicates, you can use --no-ignore to omit using the ignore rules.