Настройка ESLint от Airbnb и Nuxt.js
Установка и настройка проекта на Nuxt.js (Vue.js) с использованием линтера ESLint от команды Airbnb.
Дата публикации
15 Декабря 2020
Дата изменения
2 Марта 2021
Уникальных просмотров
Оглавление
- Устанавливаем пакеты для ESLint
- Настраиваем ESLint
- Настраиваем конфигурационный файл ESLint
- Редактируем package.json
- Решение проблемы с max-len
В этой статье я расскажу и покажу как настроить проект на Nuxt.js с использованием линтера ESLint от команды Airbnb. При создании проекта на Nuxt.js — вы можете выбрать использовать ли линтер в проекте и если да, то какой. Но я покажу, как подключить линтер в уже существующий проект.
Устанавливаем пакеты для ESLint
В кач-ве примера, я создам абсолютно чистый проект на Nuxt.js, без использования линтера или какого-нибудь TypeScript. После установки проекта, нам нужно установить некоторые пакеты для грамотной отработки линтера. Давайте их разберем перед установкой:
- eslint [npm] [Github] — Основной пакет ESLint.
- eslint-config-airbnb-base [npm] [Github] — Сам пакет с конфигами от команды Airbnb. Обратите внимание, мы используем именно eslint-config-airbnb-base , а не eslint-config-airbnb , т. к. последний разработан для фреймворка React, а мы используем Vue.js / Nuxt.js.
- eslint-plugin-import [npm] [Github] — Этот пакет будет проверять все наши импорты и будет следить за тем, чтобы все импортируемые зависимости присутствовали в проекте.
- eslint-plugin-vue [npm] [Github] — Пакет для линтерации Vue.
eslint-plugin-nuxt [npm] [Github] — Пакет для линтерации Nuxt. - eslint-import-resolver-nuxt [npm] [Github] — Пакет для разрешения импорта по умолчанию в ESLint.
Все эти пакеты ставим в devDependencies:
npm i eslint eslint-config-airbnb-base eslint-plugin-import eslint-plugin-vue eslint-plugin-nuxt eslint-import-resolver-nuxt --save-dev
Для совместной работы линтера и Vue, нужно установить сам Vue как prod зависимость:
npm i vue --save
Настраиваем ESLint
Запускаем команду настройки ESLint:
eslint --init
Далее в терминале нужно будет выбрать настройки:
- How would you like to use ESLint? (Как мы хотим использовать ESLint?)
- To check syntax only (только проверять синтаксис)
- To check syntax and find problems (проверять синтаксис и производить поиск проблем)
- To check syntax, find problems, and enforce code style (проверять синтаксис, производить поиск проблем и применять стиль кода)
- What type of modules does your project use? (Какие типы модулей использует наш проект?)
- JavaScript modules (import/export)
- CommonJS (require/exports)
- None of these
- Which framework does your project use? (Какой фреймворк использует наш проект?)
- React
- Vue.js
- None of these
- Does your project use TypeScript? (Используем ли в проекте TypeScript?)
- Yes
- No
- Where does your code run? (Где наш код запускается)
- Browser (Браузер)
- Node (Нода)
- How would you like to define a style for your project? (Как бы мы хотели определить стиль своего проекта?)
- Use a popular style guide (использовать популярное руководство по стилю)
- Answer questions about your style (ответить на вопросы о собственном стиле)
- Inspect your JavaScript file (s) (предоставить JS файлы для анализа стиля)
- Which style guide do you want to follow? (Какому руководству стиля мы хотим следовать?)
- Airbnb:https://github.com/airbnb/javascript
- Standard:https://github.com/standard/standard
- Google:https://github.com/google/eslint-config-google
- What format do you want your config file to be in? (В каком формате мы хотим использовать конфигурационный файл?)
- JavaScript
- YAML
- JSON
После этого настройщик предложит вам установить следующие зависимости:
The config that you've selected requires the following dependencies: eslint-plugin-vue@latest eslint-config-airbnb-base@latest eslint@^5.16.0 || ^6.8.0 || ^7.2.0 eslint-plugin-import@^2.22.1
Но мы их уже установили ранее, так что, пропускаем и завершаем настройку.
Настраиваем конфигурационный файл ESLint
После установки и настройки ESLint и всех остальных пакетов, в корне проекта должен появиться файл .eslintrc.js . Если этого не случилось (что будет странно), создайте его вручную. Если файл создался автоматически, то вы увидите некоторые настройки в нем.
Дефолтные настройки линтера пригодны для Vue, но не для Nuxt.js. Посему нужно внести некоторые изменения:
module.exports = { env: { browser: true, es2021: true, node: true, }, extends: [ 'eslint:recommended', 'airbnb-base', 'plugin:vue/essential', 'plugin:vue/vue3-recommended', 'plugin:nuxt/recommended', ], parser: 'vue-eslint-parser', parserOptions: { ecmaVersion: 12, sourceType: 'module', }, plugins: [ 'vue', ], rules: {}, settings: { 'import/resolver': { nuxt: { extensions: ['.js', '.vue'], }, }, }, };
Это настройки я описывал в похожей статье по настройке Nuxt.js + TypeScript + ESLint. По сути, мы расширили конфигурацию линтера правилами для Vue и Nuxt.js. Добавили настройки для импорта .js и .vue файлов и установили Vue парсер.
Редактируем package.json
На самом деле, мы уже настроили линтер и все хорошие / современные IDE подхватывают файл настроек линтера (который мы редактировали выше) и проводят линтерацию согласно заданным настройкам. Но будет удобно, если у нас будет пару команд для проверки всего проекта на соответствие правилам линтера. Для этого мы в файл package.json , в параметр scripts , добавим три строчки:
"scripts": { . "lint": "npm run lint:js", "lintfix": "eslint --fix --ext .js,.vue --ignore-path .gitignore .", "lint:js": "eslint --ext .js,.vue --ignore-path .gitignore ." },
Далее в терминале пропишем команду:
npm run lint
И в чистом Nuxt.js проекте, я получил следующий результат:

Большинство проблем, можно пофиксить командой:
npm run lintfix
Решение проблемы с max-len
Как я уже сказал, многие проблемы линтер может решить самостоятельно. Но есть и исключения, например линтерация по правилу — vue/max-len. Линтер может не устраивать длинна строки и придется решать эту проблему руками, перенося длинную строку на новую.
В конфигурационном файле .eslintrc.js , мы можем задать новую настройку:
rules: { 'max-len': ['error', { code: 120 }], 'vue/max-len': ['error', { code: 120, template: 100, }], },
Теперь длинна строки кода не должна превышать 120 символов, а длина строки в разметке — 100. Это позволит нам немного увеличить строки, что удобно например при использовании @media запросов в CSS или при вставке svg в тело страницы. Воспользоваться ли этим решением или нет — решайте сами.
На этом настройка ESLint в проекте Nuxt.js завершена.
Благодарность автору
Если по какой-либо причине вы хотите поблагодарить автора данного ресурса, вы можете это сделать одним из удобных для вас способов ниже.
Один из самых популярных способов поблагодарить автора, воспользоваться сервисом Яндекс.Деньги.
Quick Set up Eslint with Airbnb Style Guide.
As simple as setting up eslint is, it can get very confusing, especially when you want to set it up with a shared style guide. In this blog post, I would be explaining how to set up eslint with airbnb style guide and I hope it won’t take more than 5 minutes. I assume you already know what eslint is (check here if you don’t), so let’s get started with setting it up.
Installing Eslint
To set up eslint, the first thing you need to do is, install the eslint npm package (you guessed it). There a lot of resources out there that would advise you to install it globally, however, I would say install it as part of your project dependencies because you might be having some trouble adding shared style guide if you install it globally.
Run this npm install eslint —-save-dev to install eslint
Installing the style guide
The next thing is to install the style guide we want to use, Airbnb. The Airbnb style guide is identified as eslint-config-airbnb in the NPM repository. This style guide has some peer dependencies that must be installed along with it. If you don’t use React, you might want to consider installing eslint-config-airbnb-base which should have lesser peer dependencies.
Run this npm install eslint-config-airbnb —-save-dev to install airbnb style guide
Run this npm info “eslint-config-airbnb@latest» peerDependencies to list all the peer dependencies
You can either install the peer dependencies one after the other or use this shortcut if you have npm version 5+
Run this npx install-peerdeps —dev eslint-config-airbnb peer dependencies(if you have npm version 5+)
Configuring Eslint
We are going to create a configuration file( .eslintrc )for eslint, the file can either be .json or .yml , this file holds the configuration rules that eslint would use to do its linting. Since we want to make use of the Airbnb style guide, this is pretty straight forward, all we need to do is extend the style guide:
If you prefer JSON, the .eslintrc.json file should look like this:
"extends": "airbnb"
>
If you prefer YML, the .eslintrc.yml file should look like this:
extends:
- "airbnb"
Testing
To test if it is working, create a test.js file and add this line of code
var a = 4
Then go to the command line and run this ./node_modules/.bin/eslint test.js you should see the output pointing to the fact that the var keyword is not supposed to be used(according to Airbnb style guide). Note that the command above simply involves changing into the .bin folder in your node_modules and then running the eslint command line tool.
If the output gave what is expected then eslint is set up but if it does not, maybe you want to check if everything went well from the start.
I know you must be thinking, would I have to always type ./node_modules/.bin/eslint file-name every time I want to lint a file, don’t worry, you won’t. I have two workarounds for this; choose the one that suits you.
Using a lint script
The first one is for you to add a lint script to your package.json file like this:
// In your package.json
"scripts": "lint" : "./node_modules/.bin/eslint"
>
so anytime you want to lint a file, just do: npm run lint path/to/file
This is not much of a solution, let’s check the other workaround.
#vscodegang
This workaround is actually dependent on the code editor or IDE you use, I use visual studio code so I am going to discuss how to use it in vscode. This workaround is to install an extension to the code editor that would make the editor use the configuration of eslint you have to lint your codes. I personally use the Eslint extension and it is the only one I can recommend, as soon as you install it make sure you enable it and then restart vscode. If you already set up you eslint properly, when you type codes that contradict the style guide you are using, it would lint it as you type.
Setting up this workaround for any other editor or IDE is pretty much simple, just search for the extension that would enable it and how to set it up.
Conclusion
There is a lot more with regards to using eslint but as I said at the beginning of this blog post, we are just setting it up. To get more on using eslint, I have just one place I can point you to, the Eslint official documentation .
I w̵r̵o̵t̵e̵ updated this blog post with eslint was at version 5.3.0, if you find out that eslint has made some breaking changes in the installation process in some higher versions, you can let me know(ogunniyitunmise@gmail.com) so that I would update this blog post, thank you.
Держи свой код чистым с помощью ESLint
Основы самого популярного JavaScript линтера, который позволяет проводить анализ качества твоего кода.
Tools · 14.02.2019 · читать 2 мин · Автор: Alexey Myzgin
Что такое ESLint
ESLint — это линтер для языка программирования JavaScript, написанный на Node.js.
Он чрезвычайно полезен, потому что JavaScript, будучи интерпретируемым языком, не имеет этапа компиляции и многие ошибки могут быть обнаружены только во время выполнения.
ESLint поможет тебе:
- найти существующие ошибки в коде;
- избежать глупых ошибок;
- избежать бесконечные циклы в условиях цикла for;
- убедится, что все методы getter возвращают что-то;
- не разрешить выражения console.log (и аналогичные);
- проверить наличие дубликатов cases в switch ;
- проверить недоступный код;
- проверить правильность JSDoc;
и многое другое! Полный список доступен по ссылке.
Растущая популярность Prettier, как средства форматирования кода, сделала часть стилей ESLint устаревшей, но данный линтер всё еще очень полезен для выявления ошибок в коде.
ESLint очень гибок и настраиваемый, и ты можешь выбрать, какие правила использовать, или какой стиль применять. Многие из доступных правил отключены, но их можно включить в файле конфигурации .eslintrc , который может быть глобальным или локальным для твоего проекта.
Установка ESLint глобально
npm install -g eslint # создает конфигурацционный файл `.eslintrc` eslint --init # запускает ESLint проверку указанного файла eslint yourfile.js
Установка ESLint локально
npm install eslint --save-dev # создает конфигурацционный файл `.eslintrc` ./node_modules/.bin/eslint --init # запускает ESLint проверку указанного файла ./node_modules/.bin/eslint yourfile.js
Установка стилей Airbnb
Одной из самых популярных настроек для линтера является использование Airbnb JavaScript Style.
yarn add --dev eslint-config-airbnb
npm install --save-dev eslint-config-airbnb
что бы установить пакет конфигурации Airbnb и добавь в свой .eslintrc файл который находится в корне твоего проекта:
// .eslintrc "extends": "airbnb" >
Установка стилей для React
Подключить линтер для React можно легко с помощью плагина React:
yarn add --dev eslint-plugin-react
npm install --save-dev eslint-plugin-react
и добавив в свой файл .eslintrc :
// .eslintrc "extends": "airbnb", "plugins": ["react"], "parserOptions": "ecmaFeatures": "jsx": true > > >
Используй конкретные версии EcmaScript
ECMAScript меняет свою версию каждый год.
По умолчанию установлена 5-я версия, что означает стандарт до 2015 года.
Что бы включить ES6 (или выше), пропиши это в .eslintrc
// .eslintrc "parserOptions": "ecmaVersion": 6 > >
Подробное руководство по правилам можно найти на официальном сайте https://eslint.org/docs/user-guide/configuring.
Отключение правил где это необходимо
Иногда тебе может понадобится отключить правила в конкретном месте, это можно сделать так:
/* eslint-disable */ alert("test"); /* eslint-enable */
alert("test"); // eslint-disable-line
также можно отключить одно или несколько конкретных правил для нескольких строк:
/* eslint-disable no-alert, no-console */ alert("test"); console.log("test"); /* eslint-enable no-alert, no-console */
или для одной строки:
alert("test"); // eslint-disable-line no-alert, quotes, semi
eslint-config-airbnb-base
This package provides Airbnb’s base JS .eslintrc (without React plugins) as an extensible shared config.
Usage
We export two ESLint configurations for your usage.
eslint-config-airbnb-base
Our default export contains all of our ESLint rules, including ECMAScript 6+. It requires eslint and eslint-plugin-import .
- Install the correct versions of each package, which are listed by the command:
npm info "eslint-config-airbnb-base@latest" peerDependencies
If using npm 5+, use this shortcut
npx install-peerdeps --dev eslint-config-airbnb-base
If using yarn, you can also use the shortcut described above if you have npm 5+ installed on your machine, as the command will detect that you are using yarn and will act accordingly. Otherwise, run npm info «eslint-config-airbnb-base@latest» peerDependencies to list the peer dependencies and versions, then run yarn add —dev @ for each listed peer dependency.
( export PKG=eslint-config-airbnb-base; npm info "$PKG@latest" peerDependencies --json | command sed 's/[\,]//g ; s/: /@/g' | xargs npm install --save-dev "$PKG@latest" )
Which produces and runs a command like:
npm install --save-dev eslint-config-airbnb-base eslint@^#.#.# eslint-plugin-import@^#.#.#
npm install -g install-peerdeps install-peerdeps --dev eslint-config-airbnb-base
The cli will produce and run a command like:
npm install --save-dev eslint-config-airbnb-base eslint@^#.#.# eslint-plugin-import@^#.#.#
- Add «extends»: «airbnb-base» to your .eslintrc.
eslint-config-airbnb-base/legacy
Lints ES5 and below. Requires eslint and eslint-plugin-import .
- Install the correct versions of each package, which are listed by the command:
npm info "eslint-config-airbnb-base@latest" peerDependencies
Linux/OSX users can run
( export PKG=eslint-config-airbnb-base; npm info "$PKG" peerDependencies --json | command sed 's/[\,]//g ; s/: /@/g' | xargs npm install --save-dev "$PKG" )
Which produces and runs a command like:
npm install --save-dev eslint-config-airbnb-base eslint@^#.#.# eslint-plugin-import@^#.#.#
- Add «extends»: «airbnb-base/legacy» to your .eslintrc
eslint-config-airbnb-base/whitespace
This entry point only errors on whitespace rules and sets all other rules to warnings. View the list of whitespace rules here.
Improving this config
Consider adding test cases if you’re making complicated rules changes, like anything involving regexes. Perhaps in a distant future, we could use literate programming to structure our README as test cases for our .eslintrc?
You can run tests with npm test .
You can make sure this module lints with itself using npm run lint .