Eslint with error prevention only eslint airbnb config eslint standard config eslint prettier

Настраиваем автоматическое форматирование кода и проверку на ошибки при помощи Prettier и...

Настраиваем автоматическое форматирование кода и проверку на ошибки при помощи Prettier и ESLint согласно стайлгайду Airbnb.


Во время работы над последним проектом я опробовал в деле два прекрасных иструмента, ESLint и Prettier. Захотелось написать о том, что это такое, чем полезен линтер и prettier, как их настроить, и как использовать.


  • Что такое Lint?

    • ESLint в Create React App и расширение для VS Code
    • Настройка ESLint
    • Установка и подключение дополнительных плагинов ESLint

      • eslint-plugin-react
      • eslint-plugin-react-hooks
      • eslint-plugin-jsx-a11y
      • eslint-plugin-import
  • Prettier

    • Установка Prettier в проект
    • Отключаем конфликтующие с Prettier правила ESLint
    • Интеграция Prettier в VS Code
    • .prettierrc.json и .prettierignore
  • Установка правил Airbnb для ESLint


Что такое Lint?

Lint, или линтер — это инструмент для поиска ошибок в коде. Пример работы линтера в проекте Create React App, ниже:

линтер нашел ошибки в коде

Клавиатура моего ноутбука иногда срабатывает неправильно, и делает двойное нажатие клавиши, вместо однократного. В 8 и в 25 строке опечатка, вместо logo — logoo а вместо App — Appp
Линтер нашел эти ошибки и сообщил о них в терминал. Прекрасно!

Теперь можно их исправить, и все заработает как надо:

ошибки исправлены


ESLint в Create React App и расширение для VS Code

В Create React App линтер уже установлен, он называется ESLint. Именно его сообщения об ошибках мы видим в терминале.

Существует так же ESLint расширение для VS Code:

ESLint расширение для VS Code

Установив это расширение в VS Code, получим сообщения ESLint и подсветку ошибок в редакторе кода:

Сообщения об ошибках в коде, которые можно посмотреть прямо в VS Code, а не в терминале, при помощи плагина ESLint для VS Code


Настройка ESLint

У ESLint есть конфиг, в котором находятся правила, согласно которым он выполняет проверку кода. Как я говорил ранее, ESLint уже встроен в Create React App, и использует конфиг который называется eslint-config-react-app

В Create React App этот конфиг подключается к ESLint в package.json, 22 строка:

package.json

Eslint сейчас настроен так, как решили создатели CRA. Давайте инициализируем ESLint и заново сами все настроим, так, как нам необходимо. Для этого выполним команду:

$ npx eslint --init

Enter fullscreen mode

Exit fullscreen mode

Запустится мастер настройки ESLint.
Пройдем настройку согласно предложенным вариантам:

мастер настройки ESLint

В конце мастер создаст файл настроек линтера, .eslintrc.json:

файл .eslintrc.json

На этом базовая настройка линтера закончена, теперь было бы неплохо расширить его конфигурацию и подключить несколько дополнительных плагинов с правилами.


Установка и подключение дополнительных плагинов ESLint

установим правила ESLint для React:

$ npm install eslint-plugin-react --save-dev

Enter fullscreen mode

Exit fullscreen mode

Если вы используете версию React старше 17, и не импортируете React from ‘react’ можно после установки этого плагина, добавить в конфиг .eslintrc.json строку «plugin:react/jsx-runtime», тогда ESLint не будет ругаться, что ‘React’ must be in scope when using JSX

В этом случае конфиг будет выглядеть так:

Добавили "plugin:react/jsx-runtime" в конфиг .eslintrc.json


Установим правила для поддержки хуков React, eslint-plugin-react-hooks:

$ npm install eslint-plugin-react-hooks --save-dev

Enter fullscreen mode

Exit fullscreen mode

подключим их, добавив строку «plugin:react-hooks/recommended» в .eslintrc.json:

добавили "plugin:react-hooks/recommended" в .eslintrc.json


Установим правила доступности для людей с ограниченными возможностями eslint-plugin-jsx-a11y

$ npm install eslint-plugin-jsx-a11y --save-dev

Enter fullscreen mode

Exit fullscreen mode

добавляем «plugin:jsx-a11y/recommended» в .eslintrc.json:

добавили "plugin:jsx-a11y/recommended" в .eslintrc.json:


установим правила, которые будут отвечать за синтаксис импортов и экспортов eslint-plugin-import

$ npm install eslint-plugin-import --save-dev

Enter fullscreen mode

Exit fullscreen mode

добавим «plugin:import/recommended» в .eslintrc.json:

добавили "plugin:import/recommended" в .eslintrc.json

С ESLint мы пока что закончили, переходим к Prettier


Prettier

Prettier. Что это такое и зачем вообще нужно?

Prettier — это инструмент для автоматического форматирования кода.

Форматирование кода — это процесс придания коду определенного вида.

Prettier берет код, который вы ему дали, и преобразует этот код к единому стилю.

Вот простой пример:

Prettier форматирует код

Здесь у нас стандартный файл App.js из Create React App проекта, у которого я где то убрал, а где то добавил отступы и точки с запятыми в конце строк, в некоторых местах использовал длинные, плохо читаемые строки.

Prettier автоматически исправил мой код при сохранении файла, добавил нужные отступы, точки с запятыми, а длинные линии кода разбил на более короткие и лучше читаемые блоки. Теперь все выглядит лучше и опрятнее.


Установка Prettier в проект

Установка хорошо описана в официальной документации, пройдем ее вместе, по шагам.

Первым делом устанавливаем Prettier в наш Create React App проект, локально:

$ npm install --save-dev --save-exact prettier

Enter fullscreen mode

Exit fullscreen mode

Создаем пустой конфигурационный файл, .prettierrc.json в корне проекта:

$ echo {}> .prettierrc.json

Enter fullscreen mode

Exit fullscreen mode

.prettierrc.json конфиг

Отключаем конфликтующие правила ESLint

Теперь нужно сделать так, чтобы Prettier не конфликтовал с линтером. Дело в том, что когда ESLint ищет ошибки в коде, он руководствуется определенными правилами, которые хранятся в его конфиге. Эти правила отвечают как за качество кода, так и за стиль кода. Так вот, у Prettier есть свои собственные правила, которые тоже отвечают за стиль кода. Чтобы у линтера и Prettier не было конфликтов по части оформления кода, нужно отключить кофликтующие правила у линтера, чтобы за стиль кода отвечал только Prettier.
Сделать это можно очень просто, установив eslint-config-prettier

ставим:

$ npm install --save-dev eslint-config-prettier

Enter fullscreen mode

Exit fullscreen mode

Далее открываем конфиг нашего линтера, (файл .eslintrc.json), и добавляем «prettier» в конец массива:

добавляем "prettier" в конфиг .eslintrc.json

Cтрока «prettier» в конфиге .eslintrc.json отключает конфликтующие с Prettier правила ESLint.
Теперь Prettier и линтер будут корректно работать вместе.

Мы установили Prettier в наш проект. Давайте теперь добавим поддержку Prettier в VS Code.


Интеграция Prettier в VS Code

Установим расширение Prettier для VS Code:

Расширение Prettier для VS Code

После того как мы установили расширение Prettier в VS Code, можно сделать так, чтобы Prettier автоматически форматировал наш код, когда мы сохраняем файл. Для этого нужно добавить два значения в JSON конфиг VS Code, (файл settings.json).

Чтобы открыть settings.json нужно, находясь в VS Code, нажать Ctrl + Shift + P, ввести в поиск «settings» и выбрать пункт Open Settings (JSON). Откроется файл settings.json.

редактируем конфиг settings.json

Добавим в него следующие строки:

"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true

Enter fullscreen mode

Exit fullscreen mode

Первая строка устанавливает Prettier как инструмент форматирования кода по-умолчанию.
Вторая строка включает форматирование кода при сохранении файла.


.prettierrc.json и .prettierignore

Пара слов об этих двух файлах.

Для чего нужен .prettierrc.json?

.prettierrc.json — это файл конфигурации Prettier.

Перечислю базовые настройки, которые в него можно добавить:

{
  "trailingComma": "es5",
  "tabWidth": 4,
  "semi": false,
  "singleQuote": true
}

Enter fullscreen mode

Exit fullscreen mode

«trailingComma» — отвечает за висящие, (или «последние») запятые. Можно разрешить Prettier ставить их там, где это возможно, или отключить эту функцию

«tabWidth» — ширина отступа, в пробелах

«semi» — отвечает за добавление точек с запятыми в конце инструкций. Можно добавлять, можно не добавлять

«singleQuote» — отвечает за использование одинарных или двойные кавычек


Мой конфиг .prettierrc.json сейчас выглядит так:

файл .prettierrc.json

В нем я запретил использование точек с запятыми в конце строк. Такое вот личное предпочтение, при работе над персональными проектами.


В итоге, когда мы сохраняем файл, Prettier будет удалять точки с запятыми в конце строк, если они были, и менять одинарные кавычки на двойные. (замена кавычек на двойные производится по умолчанию, этим поведением можно управлять при помощи параметра «singleQuote»)

вот как это выглядит:

Alt Text

Сохранили файл — произошло форматирование кода.


.prettierignore

Файл .prettierignore существует для того, чтобы запретить Prettier форматировать определенные файлы. Какие файлы запретить форматировать, решаете вы. Я добавил туда файл .eslintrc.json, потому что не хочу, чтобы Prettier его трогал:

файл .prettierignore


Установка правил Airbnb для ESLint

Теперь, когда мы настроили ESLint и Prettier в нашем проекте, давайте установим популярный конфиг eslint-config-airbnb, который настроен с учетом стайлгайда по JavaScript от Airbnb

для этого выполним команду:

$ npm install --save-dev eslint-config-airbnb

Enter fullscreen mode

Exit fullscreen mode

и добавим «airbnb» в .eslintrc.json.
Финальный конфиг ESLint с учетом правил Airbnb будет выглядеть вот так:

финальный вариант конфига .esnlintrc.json

Чтобы ESLint не ругался на то, что у нас JSX присутствует в файлах с расширением ‘.js’, можно добавить правило

"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }]

Enter fullscreen mode

Exit fullscreen mode

в .eslintrc.json, тогда ошибки JSX not allowed in files with extension ‘.js’ не будет:

добавили правило "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }] в .eslintrc.json

Установка и настройка ESLint и Prettier закончена!


Что мы сделали:

  • разобрались с тем, что такое линтер
  • установили и настроили ESLint в Create React App проект
  • установили ESLint в VS Code
  • узнали, что такое Prettier
  • установили и настроили Prettier в нашем проекте
  • установили расширение Prettier в VS Code и настроили форматирование кода при сохранении файла
  • установили в линтер популярные правила написания JavaScript кода от Airbnb

Увидимся в новых постах!

Олег Бидзан

Олег Бидзан


Технический директор Simtech Development

В этой статье я хочу начать с самого простого и углубляться шаг за шагом. Для начала мы будем использовать простые правила и опции. Потом изучим использование конфигов и плагинов. На протяжении всего процесса вы будете получать полезные советы и информацию, чтобы на выходе создать собственное ESLint и Prettier окружение.

Как все начиналось

Вообще я не хотел использовать ESLint и Prettier, потому что Angular, который я использую в повседневной жизни, даёт мне нужные утилиты и простой инструмент форматирования кода. Но в итоге некоторые вещи заставили меня изменить свое решение об использовании ESLint и Prettier.

Во-первых, бесконечные споры о том, как писать и форматировать код. Это действительно надоевшая всем тема, по крайней мере, для меня. Личным предпочтениям тут не место. Есть более важные вещи, на которые стоит обратить внимание.

Во-вторых, я не хочу казаться беспомощным, когда коллеги начнут задавать вопросы во время демонстрации. Они потеряют интерес, если вы не отвечаете на вопросы или не сможете раскрутить тему.

В-третьих, мощь этих инструментов. Они помогают заниматься действительно важными вещами вместо того, чтобы отвлекаться от процесса, если, например, код отформатирован неправильно, на что чаще всего обращают внимание на code review.

И, в конце концов, это всё про бизнес, неважно насколько нам нравится то, что мы делаем. Это просто трата времени. Вы можете потратить его эффективнее.

Как вы заметили, у разработчиков в течение рабочего дня очень много отвлекающих факторов. Давайте устраним их, используя устоявшиеся инструменты.

Инфо Скорее всего поддержки TSLint в Angular не будет в ближайшее время т.к. TypeScript решили внедрить ESLint вместо TSLint. Команда Angular уже работает нам переездом с TSLint на ESLint. См. issue.

ESLint — это утилита, которая может анализировать написанный код. Фактически, это статический анализатор кода, и он может находить синтаксические ошибки, баги или неточности форматирования. В других языках, например, Go, это является неотъемлемой частью языка программирования.

Что я должен сделать, чтобы начать использовать ESLint?

Я рассчитываю, что у вас уже установлены node и npm, и вы знакомы с ними.

Создание рабочей папки

Перейдите в папку, где находится ваш JavaScript или TypeScript проект, или, как я, создайте тестовую папку lint-examples, где мы можем работать по ходу статьи. В операционных системах на основе Linux наберите mkdir lint-examples в командной строке и затем перейдите в созданную папку с помощью команды cd lint-examples.

Установка ESLint

Теперь давайте создадим package.json, чтобы мы могли установить ESLint. Выполнение команды npm init создаст package.json, который необходим для установки eslint в вашу папку.

Добавьте eslint в ваши npm скрипты

{
  "name": "eslint-examples",
  "version": "0.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "eslint": "eslint"
  },
  "devDependencies": {
    "eslint": "7.1.0"
  }
}

Подсказка "eslint": "eslint" в скриптах — это сокращение для node_modules/.bin/eslint.

Создайте test.js

Давайте создадим простой JavaScript-файл в папке lint-example, куда мы установили ESLint. Не переживайте о плохом форматировании примера. Нам нужно это для старта.

var foo = 1
console.log(foo)
var bar
bar = 1
function test(


    ) {
  console.log(baz)
}
var baz = 123

Первая попытка в командной строке

Если вы сейчас запустите test.js, используя ESLint, ничего не случится. По умолчанию ESLint проверяет только синтаксические ошибки. Он будет использовать ES5 по умолчанию. Описание опций парсинга можно найти по ссылке.

Если вы использовали const или let в примере выше, ESLint генерирует ошибку, потому что, как уже говорилось, ES5 выбран по умолчанию.

Подсказка Используя -- вы можете передать аргументы через npm-скрипты в командную строку eslint.

npm run eslint -- ./test.js

Становится интереснее!

В зависимости от того насколько современен ваш проект, вы должны выставить правильные опции. В наших примерах мы предполагаем, что вы хотите использовать современный ES6 синтаксис.

Давайте создадим наш первый .eslintrc.

Существует несколько способов передать конфигурации в ESLint. Я предпочитаю .eslintrc. По ссылке вы найдете другие способы.

{
  "env": {
    "es6": true
  }
}

Инфо env обязателен для глобальных переменных. Когда мы настраиваем параметры env, устанавливая es6 в true, ESLint включит глобальность для всех новых типов, таких как Set. Это так же включит ES6 синтаксис, например, let и const. Смотрите установка опций парсера.

Сейчас мы должны добавить несколько правил в наш .eslintrc

Можем ли мы просто определить правила? Да, потому что установили ESLint, который содержит множество правил из коробки. Для особых правил, таких как TypeScript или новых функций, которые не поддерживаются ESLint, мы должны установить модули eslint-config-xxx или eslint-plugin-xxx. Но мы можем вернуться к этому позже. Вы можете посмотреть правила по ссылке.

{
  "env": {
    "es6": true
  },
  "rules": {
    "no-var": "error",
    "semi": "error",
    "indent": "error",
    "no-multi-spaces": "error",
    "space-in-parens": "error",
    "no-multiple-empty-lines": "error",
    "prefer-const": "error",
    "no-use-before-define": "error"
  }
}

Если вы запустите npm run eslint, то должны получить результат в точности как ниже:

error 'foo' is never reassigned. Use 'const' instead prefer-const
error Missing semicolon semi
error Expected indentation of 0 spaces but found 4 indent
error 'bar' is never reassigned. Use 'const' instead prefer-const
error Multiple spaces found before ')' no-multi-spaces
error There should be no space after this paren space-in-parens
error There should be no space before this paren space-in-parens
error More than 2 blank lines not allowed no-multiple-empty-lines
error 'baz' was used before it was defined no-use-before-define
error 'baz' is never reassigned. Use 'const' instead prefer-const

26 problems (26 errors, 0 warnings)
20 errors and 0 warnings potentially fixable with the `--fix` option.

Мы сделали большой шаг и теперь знаем, какими должны быть наши стандарты кодирования и форматирования кода, но в реальной жизни правил, конечно же, гораздо больше.

Возможно, вы увидели в выводе результата ESLint, что 20 проблем из 26 могут быть решены автоматически. Мы вернемся к этому в следующем разделе.

ESLint и форматирование кода?

ESLint может автоматически форматировать ваш код до определенной стадии. Как вы возможно видели в выводе лога, дополнительный флаг --fix может быть использован для форматирования написанного кода, основываясь на правилах eslint. Например, пропущенная точка с запятой может быть добавлена автоматически, а несколько пустых строк подряд будут удалены. Это так же работает для других правил.

Давайте исправим код, выполнив npm run eslint -- ./ --fix

var foo = 1;
console.log(foo);
var bar;
var = 1;
function test(

) {
    console.log(baz);
}
var baz = 123;
1:1 error Unexpected var, use let or const instead no-var
3:1 error Unexpected var, use let or const instead no-var
11:1 error Unexpected var, use let or const instead no-var

3 problems (3 errors, 0 warnings)

Вы видите, что ESLint исправляет не все правила. Оставшиеся три ошибки необходимо поправить вручную, однако остальные ошибки из отчета ESLint (такие как «Пропущенная точка с запятой», «Неправильные отступы», «Множественные пробелы») были исправлены автоматически.

Обратите внимание Причина, по которой var не может быть исправлена, — в каких-то действиях с контекстом браузера. Вы можете почитать подробнее по ссылке.

В документации ESLint вы можете найти, какие правила можно активировать с помощью иконки «check mark». Код, который может быть отформатирован автоматически, подсвечивается с помощью иконки гаечного ключа.

  • Правила можно найти по ссылке.
  • Существует примерно 300 правил, и их число постоянно растет.
  • Примерно 100 из этих правил делают автоформатирование.

Всё это становится мощнее, если код форматируется вашей IDE при изменении (сохранении) файла, или если любой инструмент автоматизации, например travis-ci, может взять на себя эту задачу, когда что-то отправляется в Git.

Если ESLint может форматировать ваш код, что тогда делает Prettier?

Похоже, что ESLint хорошо выполняет некоторое форматирование кода. Как видно в примере выше, этого не достаточно. Код всё ещё выглядит недостаточно хорошо, особенно если вы посмотрите функции. Вот где зерна отделяются от плевел. ESLint прежде всего предназначен для качества кода. Prettier, как видно из названия, делает ваш код красивым. Давайте посмотрим, к чему приведет использование Prettier.

Что надо сделать, чтобы начать использовать Prettier?

Не так много. Просто добавьте в ваши npm-скрипты "prettier": "prettier" и запустите npm install prettier.

Как мы помним, этот код был отформатирован ESLint, и он не очень хорошо оформлен.

// test.js
const foo = 1;
console.log(foo);
let bar;
bar = 1;
function test(

) {
    console.log(baz);
}
const baz = 123;

После выполнения npm run prettier -- --write ./test.js код выглядит опрятнее.

const foo = 1;
console.log(foo);
let bar;
bar = 1;
function test() {
  console.log(baz);
}
const baz = 123;

Так намного лучше. Чем больше кода, тем лучше результат.

Могу ли я настраивать Prettier?

Да. Настроек в парсере Prettier не так много, как в ESLint. С Prettier вы полностью во власти парсера Prettier. Основываясь на небольшом количестве опций, он сам решает, как будет выглядеть ваш код.

Это мои настройки, которые описаны в файле .prettierrc. Полный список опций вы можете найти по ссылке. Давайте создадим .prettierrc-файл с такими опциями.

{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "arrowParens": "avoid"
}

Запускать ли ESLint и Prettier одновременно?

Не рекомендуется запускать ESLint и Prettier по отдельности, чтобы применить правила написания кода и форматирования. Более того, ESLint и Prettier будут мешать друг другу т.к. у них есть пересекающиеся правила, и это может привести к непредсказуемым последствиям. В следующем разделе мы рассмотрим эту проблему и решим ее. Если кратко, то вы просто запускаете eslint в командной строке, а prettier будет уже включаться туда.

Как всё это начиналось!

Как я писал в начале статьи, я никогда не использовал ESLint и Prettier прежде. Следовательно, я не знал, как эти утилиты работают. Как любой разработчик, я копировал наилучший кусок кода из глубин интернета в мой .eslintrc-файл без понимания, что это даст. Главной целью было, чтобы это работало.

Вот небольшой кусочек кода из моего .eslintrc-файла, который я скопировал из нескольких источников и адаптировал под себя, постепенно понимая, что делает конфиг.

Если коротко, то там настройки и плагины для ESLint, предоставленные сообществом открытого исходного кода. Мы не должны делать их сами. Главное понимать, как это работает под капотом.

.eslintrc

{
  "plugins": [
    "@typescript-eslint",
    "prettier",
    "unicorn" ,
    "import"
  ],
  "extends": [
    "airbnb-typescript/base",
    "plugin:@typescript-eslint/recommended",
    "plugin:unicorn/recommended",
    "plugin:prettier/recommended",
    "prettier",
    "prettier/@typescript-eslint"
  ],
  "parserOptions": {
    "ecmaVersion": 2020,
    "sourceType": "module"
  },
  "env": {
    "es6": true,
    "browser": true,
    "node": true
  },
  "rules": {
    "no-debugger": "off",
    "no-console": 0
  }
}

Заметка Возможно, вы заметили prettier в плагинах, и вы все еще помните, что я писал выше: «Должны ли мы одновременно запускать ESLint и Prettier для форматирования кода?» Ответ нет, потому что eslint-plulgin-prettier и eslint-config-prettier сделают всю работу за вас.

Что означают эти настройки и опции?

После того, как я заставил систему работать, то задался вопросом, а что это всё значит. Это буквально выбило меня из колеи. Если вы запустите ESLint в вашей консоли с этими опциями, то получите сообщение об ошибке, что конфига (расширения) и плагины не установлены. Но откуда мы можем знать, что устанавливать? Каждый знаком с процессом, вы находите кусок кода на StackOverflow или в каком-то репозитории и потом не знаете, как правильно запустить его.

Вы должны помнить, что все модули внутри extends и plugins могут быть установлены. Но сначала вы должны узнать, как интерпретировать соглашение об именах в свойствах, чтобы иметь возможность устанавливать их через npm.

Что такое опции «плагина»?

Плагины содержат правила написанные с использованием парсера. Это могут быть правила на рассмотрении из TC39, которые еще не поддерживаются ESLint, или специальные рекомендации по написанию кода, которые не представлены в ESLint, например, unicorn/better-regex, import/no-self-import.

Представьте, что вы хотите ввести правило, которое гласит, что в начале файла перед написанием какой-либо строки кода всегда должен быть комментарий, начинающийся со смайлика. Звучит странно, но вы можете сделать это с помощью ESLint Plugin.

// :penguin: emoji

Давайте узнаем, как интерпретировать соглашение об именах плагинов

Если имя плагина начинается не с eslint-plugin- или @ или ./, вы просто должны добавить префикс eslint-plugin-.

plugins: [
  "prettier", // npm module "eslint-plugin-prettier"
  "unicorn"   // npm module "eslint-plugin-unicorn"
]

Еще пример, работает так же:

plugins: [
  "eslint-plugin-prettier", // the same as "prettier"
  "eslint-plugin-unicorn"   // the same as "unicorn"
]

Становится немного сложнее, когда вы сталкиваетесь с именами плагинов, которые начинаются с @ (пространство имен). Как видно из приведенного ниже примера, использование / ограничено одним уровнем. Вы должны учитывать, что @mylint и @mylint/foo находятся в одном и том же пространстве имен, но это два разных плагина (npm-модуля).

plugins: [
  "@typescript-eslint", // npm module "@typescript-eslint/eslint-plugin"
  "@mylint",        	// npm module "@mylint/eslint-plugin"
  "@mylint/foo",        // npm module "@mylint/eslint-plugin-foo"
  "./path/to/plugin.js  // Error: cannot includes file paths
]

Код примера ниже такой же, как и сверху.

plugins: [
  "@typescript-eslint/eslint-plugin", // the same as "@typescript-eslint"
  "@mylint/eslint-plugin",            // the same as "@mylint"
  "@mylint/eslint-plugin-foo"         // the same as "@mylint/foo"
]

Подсказка Используйте сокращенную форму (из первого примера) вместо длинной формы (из второго примера). Главное, чтобы вы понимали, как ESLint это конвертирует внутри.

Теперь мы знаем, как работает соглашение об именах для плагинов. Установите следующие плагины ESLint через npm.

npm i eslint-plugin-prettier eslint-plugin-unicorn

В документации ESLint вы можете найти дополнительную информацию о соглашении об именах.

Для тестирования ваш .eslintrc должен выглядеть следующим образом:

{
  "plugins": [
    "prettier",
    "unicorn"
  ],
  "env": {
    "es6": true
  }
}

Prettier: ESLint плагин для форматирования кода.

Unicorn: дополнительные правила, которые не поддерживаются ESLint.

Теперь, если вы запустите npm run eslint в командной строке, вы не получите сообщение об ошибке, но также не получите и вывод ESLint. Это потому, что мы должны зарегистрировать модуль плагина в свойстве extends нашего .eslintrc-файла или применить его, активировав в разделе rules.

Давайте выясним, как интерпретировать соглашение об именах в расширениях

Прежде всего, если вы считаете, что соглашение об именах в разделе extends такое же, как и у плагинов, я должен вас разочаровать. Есть отличия. Должен честно признать, что мне потребовалось много времени, чтобы заметить разницу. Это было отчасти потому, что ESLint — сложная и обширная тема, по крайней мере, для меня.

Пока вы используете только простое имя (например, foo) без префикса пространства имен (@) или с (./to/my/config.js), принцип соглашений об именах в extends такой же, как и с параметром plugins. Таким образом, foo становится eslint-config-foo

extends: [
  "airbnb-base", // npm module "eslint-config-airbnb-base"
  "prettier"     // npm module "eslint-config-prettier"
]

идентичен

extends: [
  "eslint-config-airbnb-base", // shortform is "airbnb-base"
  "eslint-config-prettier"     // shortform is "prettier"
]

Итак, мы подошли к тому, что существуют различия в соглашении об именах между plugins и extends. Это тот случай, когда вы используете пространства имен (@) в разделе extends. Следующая конфигурация ESLint @mylint все та же, она указывает на модуль npm @mylint/eslint-config, но @mylint/foo может привести к ошибке при использовании в extends из-за отсутствия префикса eslint-config- в @mylint/eslint-config-foo.

extends: [
  "@bar",                   // npm module "@bar/eslint-config"
  "@bar/eslint-config-foo", // npm module "@bar/eslint-config-foo"
  "@bar/my-config"          // npm module "@bar/eslint-config/my-config"
]

Как я писал в введении к предыдущему разделу, следующий @mylint/my-config немного особенный, поскольку он содержит модуль npm, но в то же время он указывает изнутри ESLint на набор правил (my-config). Мы скоро это выясним. Вот официальная документация по соглашению об именах extends.

Давайте установим остальные модули npm для нашего примера.

npm i eslint-config-airbnb-base eslint-config-prettier

Примечание: возможно, вы заметили, что сначала мы установили eslint-plugin-prettier, а теперь установили eslint-config-prettier. Это разные модули, но работают только вместе. Мы обсудим это позже.

Что конкретно делает extends в .eslintrc?

Конфиг предоставляет предварительно настроенные правила. Эти правила могут состоять из правил ESLint, правил сторонних плагинов или других конфигураций, таких как синтаксический анализатор (babel, esprima, и т.д.), параметров (sourceType, и т.д.), окружений (ES6, и т.д.) и других.

Звучит неплохо? Да, потому что мы не должны делать всё сами. Продвинутые разработчики и команды уже потратили на это много времени. Всё, что нужно сделать, это активировать правила, указав конфиг или набор правил плагинов.

Где я могу найти эти наборы правил?

Есть разные способы их найти.

Во-первых, вы должны посмотреть на README.md соответствующего репозитория и прочитать именно то, что написано. Обычно, эти наборы правил называются «рекомендованными» и должны быть активированы для plugins. Для extends это не всегда необходимо.

Во-вторых, знание того, какой набор правил использовать даже без чтения README.md — вот, что я считаю гораздо более эффективным. Особенно, если файл README.md является неполным или неправильным.

По сути, вы можете сказать, что «плагины» указывают на один файл, где конфигурации (наборы правил), содержащиеся в объекте и «расширениях», указывают на наборы правил, которые находятся в разных файлах.

eslint-config-airbnb-base

eslint-config-airbnb-base (repository)
| -- index.js
| -- legacy.js
| -- whitespace.js

Вы можете активировать все конфигурации одновременно, но будьте осторожны. Вы должны заранее знать, что они делают. Обычно я предварительно изучаю связанные README.md файлы или непосредственно соответствующие наборы правил конфигурации. Довольно легко, когда вы поймете, как их активировать, верно?

Использование:

"extends": [
  "airbnb-base",            // index.js
  "airbnb-base/whitespace"  // whitespace.js
]

Держите в уме Порядок играет роль, потому что набор правил будет расширять или перезаписывать предыдущие. Так что не переусердствуйте с конфигами и плагинами. Смотрите хорошее объяснение на StackOverflow.

eslint-plugin-prettier

Теперь мы подошли к захватывающей части статьи. Как мы можем использовать Prettier напрямую в ESLint, не запуская его в качестве отдельной службы в нашей командной строке или IDE?

Мы начнём с активации eslint-plugin-prettier в разделе extends, а затем связанного с ним config eslint-config-prettier, который отвечает за деактивацию некоторых наборов правил ESLint, которые могут конфликтовать с Prettier.

eslint-plugin-mylint (repository)
| -- eslint-plugin-prettier.js (because this is specified as entrypoint in package.json)

eslint-plugin-prettier.js

module.exports = {
  configs: {
    recommended: {
      extends: ['prettier'],
      plugins: ['prettier'],
      rules: {
        'prettier/prettier': 'error'
      }
    }
  }
  ...
  ...
  ...

Использование:

"extends": [
  "plugin:prettier/recommended"
]

Подсказка Плагины должны быть зарегистрированы в plugins и активированы в extends с использованием :plugin префикс.

eslint-config-prettier

eslint-config-prettier (repository)
| -- index.js
| -- @typescript-eslint.js
| -- babel.js
| -- flowtype.js
| -- react.js
| -- standard.js
| -- unicorn.js
| -- vue.js

Использование:

"extends": [
  "prettier",                   // index.js
  "prettier/unicorn",           // unicorn.js
  "prettier/@typescript-eslint" // @typescript-eslint.js
]

Примечание Отдельно "prettier" в extends требуется для отключения некоторых правил ядра ESLint. В остальных случаях "prettier." необходимы для отключения правил в unicorn и @typescript-eslint.

Мой личный конфиг ESLint выглядит как приведенный выше пример. Я использую TypeScript и плагин Unicorn. Не хочу, чтобы они конфликтовали с ESLint. Поэтому некоторые правила TypeScript и Unicorn отключены через Prettier.

Ранее мы активировали наборы правил, которые внутренне представляют собой не что иное, как сгруппированные правила, но вам не нужно использовать комбинированный набор правил. Вы также можете изменить или отключить отдельные правила.

Активировать всё самостоятельно вместо использования набора правил не имеет смысла. Но часто случается так, что вы не согласны с тем или иным правилом или его настройками. В этом случае вы можете отключить одно правило.

.eslintrc

"rules": {
  "unicorn/prevent-abbreviations": "off"
}

Итак, вернёемся к нашему тестовому примеру. Теперь наш .eslintrc-файл должен выглядеть следующим образом:

{
  "plugins": [
    "prettier",
    "unicorn"
  ],
  "extends": [
    "airbnb-base",
    "plugin:unicorn/recommended",
    "plugin:prettier/recommended",
    "prettier",
    "prettier/unicorn"
  ],
  "env": {
    "es6": true,
    "browser": true
  },
  rules: {
    "unicorn/prevent-abbreviations": "off"
  }
}

Стратегия При переходе на ESLint может случиться так, что в выводе ESLint отображается много ошибок. Правка по ходу дела может занять много времени или даже привести к побочным эффектам. Если вы хотите переходить постепенно, рекомендуется оставить правила в режиме warning, а не error.

Если вы теперь запустите наш пример через ESLint, используя npm run eslint -- --fix, Prettier будет выполняться через ESLint, так что вам потребуется только одна команда для запуска обоих инструментов.

Как мы можем интегрировать это в IDE?

Все современные IDE (IntelliJ и VS Code) поддерживают ESLint. Важно отметить, что в некоторых случаях вы должны передавать параметр --fix в качестве аргумента в настройках IDE, чтобы всё работало автоматически.

Почему существуют разные типы парсеров «ESLint»?

ESLint поддерживает только новый синтаксис JavaScript, который находится на финальной стадии в TC39. Возможно, не многие знают это, но компилятор Babel поддерживает функции, которые ещё не находятся на финальной стадии. Хорошо известная функция — decorator. От функции, на которой был основан Angular, отказались. Новая же функция имеет другой синтаксис и семантику. Предыдущая функция находится на второй стадии, а новая — на раннем этапе.

В этом случае ESLint вам не поможет. Либо вам нужно найти подходящий плагин для него, либо вы пишете свой собственный плагин eslint, который использует, например, анализатор babel вместо анализатора espree, который является анализатором по умолчанию в ESLint.

Смотрите настройки eslint-parser.

Как насчёт Angular и ESLint?

Команда Angular придерживается мнения, что нам следует подождать с применением ESLint. Это допустимо, потому что они хотят сделать переход как можно более плавным, но если вы всё же хотите попробовать, вот несколько советов.

Производительность и ESLint?

Может случиться, что ESLint не так эффективен, как можно было бы ожидать в некоторых частях кода, но это нормально и может произойти также в TSLint. Для решения проблемы вы можете использовать внутреннее кэширование ESLint или другого демона ESLint. Здесь вы можете найти очень полезные советы, см. пост на StackOverflow.

Prettier существует только для Javascript?

Prettier официально поддерживает несколько других языков. К ним относятся PHP, Ruby, Swift и так далее. Кроме того, существуют плагины сообщества для таких языков как Java, Kotlin, Svelte и многих других.

Как насчет ESLint v7?

Все примеры в нашей статье изначально были основаны на версии ESLint v6, но недавно была выпущена версия ESLint v7. Не волнуйтесь, даже в версии 7 ESLint работает без каких-либо изменений. Если вас интересует, что было изменено или добавлено, вы можете ознакомиться с примечаниями к выпуску ESLint v7.

Перевод статьи «Setting up efficient workflows with ESLint, Prettier and TypeScript»

ESLint + Prettier + Airbnb Style Guide Setup for VS Code

ESLint and Prettier plugins for VS Code

ESLint uses the ESLint library installed in the opened workspace folder. If the folder doesn’t provide one the extension looks for a global install version.

  1. Install ESLint plugin.

    ext install dbaeumer.vscode-eslint

  2. It is recommended to install ESLint locally in the project folder. Run the following command in the workspace folder:

    npm install eslint

    or

    npm install eslint --save-dev

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

  1. Install Prettier plugin.

    ext install esbenp.prettier-vscode

  2. Configure Prettier global settings. Open File -> Preferences -> Settings (hotkey — Ctrl + ,).

    • search for default formatter and set it to esbenp.prettier-vscode
    • enable ‘Format on save’
    • set other settings if needed

Install packages

  1. Create a package.json.

    npm init

  2. Install dev dependencies. eslint-plugin-prettier — runs Prettier as an ESLint rule and reports differences as individual ESLint issues. eslint-config-prettier — turns off all rules that are unnecessary or might conflict with Prettier.

    npm i -D eslint prettier eslint-plugin-prettier eslint-config-prettier

  3. Install package for Airbnb Style Guide.

    npx install-peerdeps --dev eslint-config-airbnb

Configuration files

Prettier

There’s no need to set up a configuration file for Prettier. If present, it will be used instead of global settings.

  1. Create a .prettierrc file.

  2. Set the rules you want as follows:

    All possible rules can be looked up here.

ESLint

  1. Press Ctrl + Shift + P to open Command Palette and find ‘ESLint: Create ESLint configuration’. Run the command.

  2. There will a bunch prompt questions. Answer as required for the project.

Set up ESLint to use Airbnb Style Guide.

Might want to create a .prettierignore file and add .eslintrc.js (json/yaml) file to it, so it doesn’t remove quotes from the keys.

  1. If there’s no «node»: true set in «env», set it and restart VS Code. Otherwise ESLint generates a non-undef error due to undefined module.

    "env": {
       "browser": true,
       "es2020": true,
       "node": true,
    },
    
  2. Edit ‘extends’:

    "extends": ["airbnb", "prettier"],

  3. Add plugins:

    "plugins": ["prettier"],

  4. To enable Prettier rules for ESLint, add this to the rules. Possible values: «error», «warn», «off».

    "prettier/prettier": "error",

  5. Add additional rules if needed. List of available rules here.

References

  • VSCode ESLint, Prettier & Airbnb Style Guide Setup, Tutorial by Traversy Media
  • ESLint plugin page
  • Prettier plugin page
  • ESLint Getting Started
  • eslint-config-airbnb package
  • ESLint rules
  • Prettier rules

In this article I would like to start very easily and go into more depth from topic to topic. In the first step we will use simple rules and options. Then we will learn the correct use of configs and plugins. During the whole learning process you will get useful tips and information so you will be able to build your own ESLint and Prettier environment.

How it all began

Actually I did not want to use ESLint and Prettier because I never felt the need for it because Angular, which i use in my daily life, brings a linting tool and a simple code formatter. But in the end several other things made my decision to use ESLint and Prettier in a more professional way.

First the endless discussions how code should be written or formatted. This is a really annoying subject, for me at least. Personal preferences should go away here. There are more important things to consider.

Secondly, if I want to introduce this to the team, team members will definitely ask me questions and I don’t want to stand there helplessly. It can happen that colleagues lose interest if you do not answer questions or if you cannot promote it.

Thirdly, the power of these tools. It helps you to focus on the essentials in your daily life instead of consistently being forced out of your flow because of for example code has been formatted incorrectly which is mostly reported by a colleague in a code-review.

At the end of the day its all about business no matter how much fun we have in what we do. It is just waste of time. You can spend your time better.

As you can see, for a developer there are many disruptive factors in daily business. Let’s eliminate these disturbances together based on established web tools.

Info: There will be maybe no TSLint with Angular in the near future because TypeScript decided to support ESLint instead of TSLint. The Angular Team is currently working on a migration from TSLint to ESLint. See here.

What is ESLint and how can it help us?

ESLint is a tool which can analyze written code. Basically it is a static code analyzer and it can find syntax errors, bugs or styling improvements. In other languages such as Go is the a core part of the programming language.

What do I need to get started with ESLint?

I assume that you have node and npm installed on your operating system and are familiar with it.

Create a playground directory

You should change into a directory where your JavaScript or TypeScript project is or like me create a test directory «lint-examples» where we can work on it according to this article. On a Linux-based operating system just type mkdir lint-examples in the command-line and then change to this directory with cd lint-examples.

Install ESLint

Now let’s create a package.json so we can install ESLint. Execute the following command: npm init create a package.json which is required for installing eslint in your directory.

Add eslint to your npm scripts

<>Copy

{ "name": "eslint-examples", "version": "0.0.0", "description": "", "main": "index.js", "scripts": { "eslint": "eslint" }, "devDependencies": { "eslint": "7.1.0" } }

Tip: "eslint": "eslint" in scripts is a shortcut for node_modules/.bin/eslint

Create test.js

Now let’s create a simple JavaScript file in lint-examples directory where we can apply ESLint on. Don’t worry about why the code sample is weirdly formatted. We need this as a starting point.

<>Copy

var foo = 1 console.log(foo) var bar bar = 1 function test( ) { console.log(baz) } var baz = 123

First try on command-line

If you now run the test.js file through ESLint, nothing will happen. By default, ESLint will only check for syntax errors. It will use ES5 as the default option. See ESLint specifying parser options.

If you had used const or let in the above code example, ESLint would have thrown an error because as already mentioned ES5 is the default setting.

Tip: with -- you can pass arguments trough npm scripts to the eslint command line service.

<>Copy

npm run eslint -- ./test.js

Now it is getting Interesting!

Depending on how modern your project is, you should set the right options. In our examples we assume that you want to use the modern ES6 syntax.

Let’s create our first .eslintrc

There are several ways to provide a configuration to ESLint. I prefer the .eslintrc. Here you can find other formats: Configuration-File Formats

<>Copy

{ "env": { "es6": true } }

Info: env is required for global variables. When we configure env with es6 set to true, ESLint will enable the globals for the new types such as Set. It will also enable the ES6 syntax such as let and const.
See ESLint specifying-parser-options.

Now we should add some rules to our .eclintrc

Can we just define rules? Yes we can because we have installed ESLint and it brings lot of rules out-of-the-box. For special rules like TypeScript or new features that are not supported by ESLint, we have to install either a eslint-config-xxx or a eslint-plugin-xxx module. But we will come to that later. The rules can be found here: ESLint-Rules.

<>Copy

{ "env": { "es6": true }, "rules": { "no-var": "error", "semi": "error", "indent": "error", "no-multi-spaces": "error", "space-in-parens": "error", "no-multiple-empty-lines": "error", "prefer-const": "error", "no-use-before-define": "error" } }

If you now run npm run eslint you should get roughly the following output.

<>Copy

error 'foo' is never reassigned. Use 'const' instead prefer-const error Missing semicolon semi error Expected indentation of 0 spaces but found 4 indent error 'bar' is never reassigned. Use 'const' instead prefer-const error Multiple spaces found before ')' no-multi-spaces error There should be no space after this paren space-in-parens error There should be no space before this paren space-in-parens error More than 2 blank lines not allowed no-multiple-empty-lines error 'baz' was used before it was defined no-use-before-define error 'baz' is never reassigned. Use 'const' instead prefer-const 26 problems (26 errors, 0 warnings) 20 errors and 0 warnings potentially fixable with the `--fix` option.

Now we are a big step further and know how our coding and styling guidelines should be, but in a real life there are of course more rules. I just wanted to show you how easy it is to configure your own rules.

Maybe you noticed in ESLint’s output that 20 problems of 26 can be solved automatically. We will come to that in next section.

ESLint and code formatting?

Until a certain point, ESLint can format your code automatically. As you may have noticed in the above log output, an additional --fix argument can be used to format written code based on eslint rules. For example if a semicolon is missing it will be added automatically, if there are multiple empty lines it will be removed. The same applies to other fixable rules.

Let’s fix the code by executing: npm run eslint -- ./ --fix

<>Copy

var foo = 1; console.log(foo); var bar; var = 1; function test( ) { console.log(baz); } var baz = 123;

<>Copy

1:1 error Unexpected var, use let or const instead no-var 3:1 error Unexpected var, use let or const instead no-var 11:1 error Unexpected var, use let or const instead no-var 3 problems (3 errors, 0 warnings)

You have seen that not all rules can be fixed by ESLint. For the remaining 3 errors you have to do this manually but the other reported errors by ESLint such as «Missing semicolon», «Expected indentation», «Multiple spaces», and so on were fixed automatically!

Note: The reason why «var» cannot be fixed has something to do with the browser context. You can find more information here.

In the ESLint documentation you can find which rules can be activated with a «check mark» icon. Code that can be auto-formatted is highlighted with a wrench icon.

  • The rules can be found here: ESLint-Rules.
  • There are almost 300 rules and it is constantly growing
  • About 100 of these are auto-formatting rules

The whole thing becomes even more powerful if the code is formatted by your IDE on file-change (save) or if any pipeline tool such as travis-ci can take over this task when something is pushed by Git.

Knowing that ESLint can format your code, what does Prettier even do?

It seems that ESLint does some code formatting as well. As seen in the code example above, it does not go far enough. The code does not look very nice, especially when you look at the function. This is where the wheat is separated from the chaff. ESLint is primarily intended for code quality. Prettier, as the name implies, makes your code Prettier. Let’s see how far Prettier will take us.

What do I need to get started with Prettier?

Not much. You just need to add the following to your NPM scripts "prettier": "prettier" and run npm install prettier.

As we can remember, this code was formatted by ESLint and it is not well formed.

<>Copy

// test.js const foo = 1; console.log(foo); let bar; bar = 1; function test( ) { console.log(baz); } const baz = 123;

When we apply npm run prettier -- --write ./test.js the code format becomes even better.

<>Copy

const foo = 1; console.log(foo); let bar; bar = 1; function test() { console.log(baz); } const baz = 123;

That’s much better. The larger the code base, the greater the benefit.

Can I also set options with Prettier?

Yes you can. The options for the Prettier parser are by far not as extensive as ESLint’s. With Prettier, you are almost at the mercy of the Prettier parser. It decides based on a few options how your code should look like in the end.

This are my settings which is defined in .prettierrc. The full list of code-style options can be found on prettier-options. Let’s create a .prettierrc file with these options.

<>Copy

{ "semi": true, "trailingComma": "all", "singleQuote": true, "printWidth": 80, "tabWidth": 2, "arrowParens": "avoid" }

Do we need to start ESLint and Prettier at the same time?

It is not desirable to start ESLint and Prettier separately to apply coding and format rules. Furthermore, ESLint and Prettier would get in each other’s way because they have overlapping rules and this could lead to unexpected behavior. In the next section this problem is addressed and will be solved. In short you will just call eslint in our command-line and prettier will be included.

Back to how it all began!

As I described at the beginning of this article, I had never used ESLint and Prettier before. Therefore I did not know how to get the whole tooling working. Like every developer, I copied the best possible code snippet from the depths of the Internet into my .eslintrc without knowing what it actually does. The main thing was to get it working.

Here is a little snippet from my .eslintrc config which was originally copied from several sources and adapted by me over time as I understood what the config does.

In short, there are configs and plugins for ESLint provided by the open source community. We don’t have to do it all ourselves. The main thing is to know what is happening under the hood.

.eslintrc

<>Copy

{ "plugins": [ "@typescript-eslint", "prettier", "unicorn" , "import" ], "extends": [ "airbnb-typescript/base", "plugin:@typescript-eslint/recommended", "plugin:unicorn/recommended", "plugin:prettier/recommended", "prettier", "prettier/@typescript-eslint" ], "parserOptions": { "ecmaVersion": 2020, "sourceType": "module" }, "env": { "es6": true, "browser": true, "node": true }, "rules": { "no-debugger": "off", "no-console": 0 } }

Note: maybe you noticed prettier in the plugins section and you still remember when I mentioned above: «Do we have to execute ESLint and Prettier for code formatting at the same time?» The answer is no because eslint-plulgin-prettier and eslint-config-prettier will do this job for us.

What do these settings and options mean?

After I made it work, I wondered what it all meant. Literally, it knocked me out. If you would run ESLint on your command line now with these options, an error would be thrown that the configs (extends) and plugins are not installed. But how do we know what to install? Everybody knows this, you find a code snippet on Stackoverflow or in some repositories and then you don’t know how to install them.

You can keep in mind that all the modules inside of extends and plugins can be installed. But first you have to know how to interpret the naming convention within the properties to be able to install them via npm.

What are the «plugins» options?

Plugins contain rules that have been written by using a parser. These can be proposal rules from TC39 that are not yet supported by ESLint or special coding guidelines that are not provided by ESLint such as unicorn/better-regex, import/no-self-import.

Imagine that you want to introduce a rule which says that always at the beginning of a file, before any line of code is written, a comment should start with a emoji code. Sounds weird but you can do that with ESLint Plugin.

<>Copy

// :penguin: emoji

Let’s find out how to interpret plugin naming convention

As long as the plugin name does not start with eslint-plugin- or @ or ./ then you have to just prefix the plugin name with eslint-plugin-.

<>Copy

plugins: [ "prettier", // npm module "eslint-plugin-prettier" "unicorn" // npm module "eslint-plugin-unicorn" ]

This is the same as above example and works as well:

<>Copy

plugins: [ "eslint-plugin-prettier", // the same as "prettier" "eslint-plugin-unicorn" // the same as "unicorn" ]

It gets a little bit more complicated when you come across plugin names that start with a @ (namespace). As you can see in the example below, the use of / is limited to one level. You should consider that @mylint and @mylint/foo are under the same namespace but they are two different plugins (npm modules).

<>Copy

plugins: [ "@typescript-eslint", // npm module "@typescript-eslint/eslint-plugin" "@mylint", // npm module "@mylint/eslint-plugin" "@mylint/foo", // npm module "@mylint/eslint-plugin-foo" "./path/to/plugin.js // Error: cannot includes file paths ]

The code example below it the same as above.

<>Copy

plugins: [ "@typescript-eslint/eslint-plugin", // the same as "@typescript-eslint" "@mylint/eslint-plugin", // the same as "@mylint" "@mylint/eslint-plugin-foo" // the same as "@mylint/foo" ]

Tip: Use the short form (first example) instead of the long form (second example). The important thing is that you know how ESLint converts it internally.

We now know how the naming convention works for plugins. Install the following ESLint plugins via NPM.

<>Copy

npm i eslint-plugin-prettier eslint-plugin-unicorn

In the ESLint documentation you can find further information about the naming convention, see plugin namingconvention.

For testing purposes your .eslintrc should look like this.

<>Copy

{ "plugins": [ "prettier", "unicorn" ], "env": { "es6": true } }

Prettier: ESLint plugin for formatting code. See here.

Unicorn: Additional rules which are not supported by ESLint. See here.

Now if you run npm run eslint on your command-line, you will not get an error but also not a lint output. This is because we have to register the plugin module within the extends property of our .eslintrc or apply it by activating them in the rules section.

Let’s find out how to interpret the extends naming convention

First of all, if you think the naming convention of the extends section is the same as plugins, I have to disappoint you. There are differences. I must honestly admit that it took me a long time to notice the difference. This was partly because ESLint is a complex and extensive topic, at least for me.

As long as you only use the simple name (like foo) without a prefixed namespace (@) or with a path (./to/my/config.js) the principle of the naming conventions in extends is the same as with the plugins option. So foo becomes eslint-config-foo

<>Copy

extends: [ "airbnb-base", // npm module "eslint-config-airbnb-base" "prettier" // npm module "eslint-config-prettier" ]

is equal to

<>Copy

extends: [ "eslint-config-airbnb-base", // shortform is "airbnb-base" "eslint-config-prettier" // shortform is "prettier" ]

Now we come to the point where differences between the plugins and extends naming conventions exist. This is the case when you use namespaces (@) in extends section. The following @mylint ESLint config is still the same, it points to @mylint/eslint-config NPM module but @mylint/foo can lead to an error when it is used in extends because omitting the prefix eslint-config- in @mylint/eslint-congif-foo can result in an error.

<>Copy

extends: [ "@bar", // npm module "@bar/eslint-config" "@bar/eslint-config-foo", // npm module "@bar/eslint-config-foo" "@bar/my-config" // npm module "@bar/eslint-config/my-config" ]

As I wrote in the introduction to the previous section, the following @mylint/my-config is a bit special because it contains an NPM module but at the same time it points internally from ESLint perspective to a rule set (my-config). We will clear this up shortly. Here is the official documentation of the naming convention of extends, see shareable-configs

Let’s install the rest the NPM modules for our example app.

<>Copy

npm i eslint-config-airbnb-base eslint-config-prettier

Note: You may have noticed that we installed eslint-plugin-prettier earlier and now we have installed eslint-config-prettier. These two modules are two different things but only work together. We will discuss this later.

What does extends exactly do in .eslintrc?

A config provides preconfigured rules. These rules can consist of ESLint rules, third party plugin rules or other configurations such as the parser (babel, esprima, …), options (sourceType, …), env (ES6, …), and so on.

Sounds good? Yes, this is good for us because we don’t have to do this by ourselves. Smart developers and teams have invested a lot of time to provide this to us. All we have to do is activate them by pointing to a config or to a plugin rule set.

Where can I find these rule sets?

There are different ways to find them!

Firstly, you should look at the README.md of the relevant repository and read exactly what is written. Usually these rule sets are called «recommended» and must be activated for plugins. For the extends, it is not always necessary.

Secondly, knowing which rule set to use without reading the README.md is which I personally find much more effective. It is useful if the README.md is incomplete or incorrect.

Basically you can say that «plugins» point to a single file where the configurations (rule sets) are contained in an object and «extends» points to rule sets which are in different files.

eslint-config-airbnb-base

<>Copy

eslint-config-airbnb-base (repository) | -- index.js | -- legacy.js | -- whitespace.js

You can activate all configurations at once, but be careful with that. You should find out in beforehand what they do. I explained that before by looking into related README.md or directly in the corresponding config rule set. Pretty easy once you figure out how to activate them, right?

Usage:

<>Copy

"extends": [ "airbnb-base", // index.js "airbnb-base/whitespace" // whitespace.js ]

Keep in mind: The order plays a role because a ruleset will extend or overwrite the previous ones. So do not overdo with configs and plugins. See good explanation on Stackoverflow.

eslint-plugin-prettier

Now we come to the exciting part of the article. How we can use Prettier directly in ESLint without running it as a separate service on our command line or IDE.

We start by activating the eslint-plugin-prettier in the extends section and then the related config eslint-config-prettier which is responsible for deactivating some ESLint rule sets which can conflict with Prettier.

<>Copy

eslint-plugin-mylint (repository) | -- eslint-plugin-prettier.js (because this is specified as entrypoint in package.json)

eslint-plugin-prettier.js

<>Copy

module.exports = { configs: { recommended: { extends: ['prettier'], plugins: ['prettier'], rules: { 'prettier/prettier': 'error' } } } ... ... ...

Usage:

<>Copy

"extends": [ "plugin:prettier/recommended" ]

Tip: Plugins have to be registered in plugins and activated in extends using the :plugin prefix.

eslint-config-prettier

<>Copy

eslint-config-prettier (repository) | -- index.js | -- @typescript-eslint.js | -- babel.js | -- flowtype.js | -- react.js | -- standard.js | -- unicorn.js | -- vue.js

Usage:

<>Copy

"extends": [ "prettier", // index.js "prettier/unicorn", // unicorn.js "prettier/@typescript-eslint" // @typescript-eslint.js ]

Note: The standalone «prettier» in extends is necessary here because it disables certain ESLint core rules. The others are necessary for disabling rules in unicorn and @typescript-eslint.

My personal ESLint config looks like the above usage example. I use TypeScript and the Unicorn plugin. I don’t want them to conflict with ESLint. Therefore, certain rules of TypeScript and Unicorn are disabled via Prettier.

Previously we have activated rule sets which are internally nothing else than grouped rules, but you don’t have to use a combined rule set. You can also change or disable individual rules.

Activating everything yourself instead of using a rule set makes no sense. But it often happens that you don’t agree with one or the other rule or its setting. In this case you can deactivate a single rule. See example.

.eslintrc

<>Copy

"rules": { "unicorn/prevent-abbreviations": "off" }

So, we come back to our test example. Now our .eslintrc should look like this.

<>Copy

{ "plugins": [ "prettier", "unicorn" ], "extends": [ "airbnb-base", "plugin:unicorn/recommended", "plugin:prettier/recommended", "prettier", "prettier/unicorn" ], "env": { "es6": true, "browser": true }, rules: { "unicorn/prevent-abbreviations": "off" } }

Strategy: During a transition to ESLint it can happen that many errors are displayed in ESLint output. Adjusting them immediately can take a lot of time or can even lead to side effects. If you want to have a smooth periodic transition, it is recommended to leave the rules in the warning mode instead of in error. See configuring rules.

If you now run our example code through ESLint with npm run eslint -- --fix, Prettier will be executed through ESLint so that you only need one command to run both.

How we can this be integrated into an IDE?

At this point I don’t want to write a tutorial about how to activate ESLint in a IDE of your choice. In any case you can say that all modern IDEs (IntelliJ and VS Code) support ESLint. It is important to note that you have to pass in some cases the --fix parameter as an argument in your IDE settings to make everything work automatically.

Why do different types of «ESLint» parsers exist?

ESLint only supports new JavaScript syntax that reached the final stage in TC39. Maybe not many people know this, but the Babel compiler supports features that are not in the final stage. A well-known feature is the decorator feature. The one Angular is based on was abandoned. The new one has different syntax and semantics. The old one reached stage 2 and the new one is in early state.

In this case ESLint will not help you. Either you have to find the right plugin for it or you write your own eslint plugin which uses for example the babel parser instead of the espree parser which is the default parser of ESLint.

See eslint-parser settings.

How about Angular and ESLint?

The Angular Team hold the opinion that we should wait with the rollout of ESLint. This is legitimate because they want to make it as smooth as possible but if you still want to try it, here are some suggestions. See Github.

Performance and ESLint?

It can happen that ESLint is not as performant as one would expect in some code parts, but that’s normal and can happen also in TSLint. To solve this problem you can use the internal caching of ESLint or another ESLint deamon. Here you can find very useful tips, see Stackoverflow issue.

Does Prettier exist only for Javascript?

Prettier officially supports several other languages. These include PHP, Ruby, Swift, and so on. Furthermore there are community plugins for the following languages like Java, Kotlin, Svelte and many more.

What about ESLint v7?

All examples in our article were originally based on version ESLint v6 but recently ESLint v7 has been released. Don’t worry, even in version 7 ESLint works without having to change anything. If you are interested in what has changed or been added you can check out release notes of ESLint v7.

Example repo in a comprehensive way

My personal open-source project https://github.com/pregular/core also motivated me to use ESLint and Prettier.

Conclusion

I think you don’t need to know more about ESLint and Prettier. From now on you can do the whole thing by yourself. The important thing is that you practice it over and over again so you can solidify that knowledge.

I would like to thank the InDepth community for having published my article. A big thanks goes here to Lars Gyrup Brink Nielsen who supported me on my first article

The ratio of time spent reading (code) versus writing is well over 10 to 1 … (therefore) making it easy to read makes it easier to write. -Bob Martin, Clean Code

Formatting code and adhering to style guides can be a time-consuming and meticulous task. I remember when I first started programming, I would count the number of times I pressed the space bar when I wanted to indent on a new line. And at the end of every line, I would check for semi-colons and trailing commas. Thankfully, those days are over. I have found two well-known extensions that can scan your code and reformat it to a very legible and attractive style.

11/11/2018 UPDATE:

Paulo Ramos created an awesome shell script for this: https://github.com/paulolramos/eslint-prettier-airbnb-react

Prettier

Prettier icon

Prettier is an opinionated code formatter. It supports many languages and integrates with most code editors. You can also set your preferences in the options. Some of the options include tab width, trailing commas, bracket spacing, etc.

I don’t write the best-looking code, but with Prettier I no longer have to worry about that. After a long session of furiously hacking away on my keyboard, I can save my file and then *poof* — it auto-magically formats my code!

React code

Prettier doing work! 💁

ESLint

ESLint icon

ESLint, is program that runs through your code and analyzes it for potential errors. The extension is highly configurable, with an assortment of built-in options for matching your company’s style guide. It can highlight errors while you type in your editor, as well as display an itemized list of errors in your console.

code running in console

Itemized ESLint errors in the console

Combining Prettier with ESLint + Airbnb Style Guide

We will set this up so that Prettier will be our main extension for code formatting (based on the ESLint rules we define). Our goal will be to disable all formatting rules inside ESLint so that we will only use it for errors, and have Prettier format all our code instead.

I would also like to preface that at the time of this writing (June 2018), this will not work if you install the libraries globally. In order for this to work, you will have to install ESLint and the other dependencies locally to your project (preferably under devDependencies).

Before we begin, you will have to install npm and then npx.

  1. Download the ESLint and Prettier extensions for VSCode.
  2. Install the ESLint and Prettier libraries into our project. In your project’s root directory, you will want to run: npm install -D eslint prettier
  3. Install the Airbnb config. If you’re using npm 5+, you can run this shortcut to install the config and all of its dependencies: npx install-peerdeps --dev eslint-config-airbnb
  4. Install eslint-config-prettier (disables formatting for ESLint) and eslint-plugin-prettier (allows ESLint to show formatting errors as we type) npm install -D eslint-config-prettier eslint-plugin-prettier
  5. Create .eslintrc.json file in your project’s root directory:

{ "extends": ["airbnb", "prettier"], "plugins": ["prettier"], "rules": { "prettier/prettier": ["error"] }, }

  1. Create .prettierrc file in your project’s root directory. This will be where you configure your formatting settings. I have added a few of my own preferences below, but I urge you to read more about the Prettier config file

{ "printWidth": 100, "singleQuote": true }

  1. The last step is to make sure Prettier formats on save. Insert "editor.formatOnSave": true into your User Settings in VSCode.

Congratulations, you did it!

You were able to mediate the conflicting differences between the two, and now they are the best of friends! Our linter will allow us to detect bugs early, and our formatter will help us maintain consistency throughout our codebase. With both these extensions working side-by-side, we should be able to build clean and maintainable code. Your boss will thank you, your peers will thank you, and low-key — Microsoft will probably thank you 🙃

If you have any recommendations or tips, I would love to hear more! 👂

Also, check out my previous post about Essential Customizations for VSCode!

Понравилась статья? Поделить с друзьями:
  • Eslint parsing error unexpected token function
  • Eslint parsing error unexpected token expected
  • Eslint parsing error type expected
  • Eslint parsing error the keyword interface is reserved
  • Eslint parsing error the keyword export is reserved