- Настраиваем stylelint по код гайду Standart (AirBnB), вместе с Prettier, Husky и lint-staged
- Конфиг stylelint
- Настраиваем VS Code
- Команды для запуска
- Настраиваем Husky и lint-staged
- Заключение
- vscode-stylelint
- Installation
- Disable VS Code’s Built-In Linters (optional)
- Usage
- Migrating from vscode-stylelint 0.x/Stylelint 13.x
- ⚠️ Stylelint 13.x and Prior is No Longer Supported
- ⚠️ Stylelint is No Longer Bundled
- ⚠️ Only CSS and PostCSS are Validated by Default
- Extension Settings
- stylelint.enable
- stylelint.config
- stylelint.configFile
- stylelint.configBasedir
- stylelint.customSyntax
- stylelint.reportDescriptionlessDisables
- stylelint.ignoreDisables
- stylelint.reportNeedlessDisables
- stylelint.reportInvalidScopeDisables
- stylelint.validate
- stylelint.stylelintPath
- stylelint.packageManager
- stylelint.snippet
- editor.codeActionsOnSave
- Commands
- Troubleshooting
- Contributors
- Sponsors
- Backers
- vscode-stylelint-plus
- Installation
- Optional (but recommended) setup
- Usage
- Extension settings
- stylelint.enable
- stylelint.autoFixOnSave
- stylelint.configOverrides
- stylelint.config
- stylelint.useLocal
- stylelint.disableErrorMessage
Настраиваем stylelint по код гайду Standart (AirBnB), вместе с Prettier, Husky и lint-staged
Stylelint — это гибкий инструмент для линтинга стилей, который не только отлавливает ошибки, но и помогает соблюдать соглашения по стилю кода и применяемым практикам.
В этой статье я расскажу, как настроить:
- Базовый конфиг для stylelint с правилами Prettier, код гайдом Standart (AirBnB) и rational order.
- Форматирование при сохранение файлов и с помощью сочетания клавиш shift+option+F в VS Code.
- Запуск линтера для изменённых файлов при создании коммита с помощью Husky и lint-staged.
Конфиг stylelint
Установим все необходимые пакеты:
npm i stylelint stylelint-scss stylelint-config-standard stylelint-order stylelint-config-rational-order prettier stylelint-config-prettier stylelint-prettier --save-dev
Что делает каждый из плагинов:
- stylelint — сам линтер,
- stylelint-scss — плагин для работы с .scss файлами,
- stylelint-config-standard — стандартный конфиг для stylelint, который включает в себя стайл гайд AirBnB и другие общепринятые принципы,
- stylelint-order — плагин для проверки порядка свойств,
- stylelint-config-idiomatic-order — правила порядка свойств,
- prettier — Prettier для форматирования кода,
- stylelint-prettier — для форматирования кода с помощью Prettier,
- stylelint-config-prettier — отключает правила, конфликтующие с Prettier.
Теперь настроим конфиг для stylelint, для этого создайте файл .stylelintrc.js :
module.exports = extends: ["stylelint-config-standard", "stylelint-config-rational-order", "stylelint-prettier/recommended"], plugins: ["stylelint-order", "stylelint-scss"], rules: // Дополнительные правила > >;
Настраиваем VS Code
Чтобы VS Code подсвечивал ошибки в стилях в соответствии с конфигурацией stylelint, надо установить плагин stylelint в VS Code, а так же добавить настройки для рабочей области в VS Code .vscode/settings.json :
"scss.validate": false, "css.validate": false, "less.validate": false, "editor.codeActionsOnSave": "source.fixAll.stylelint": true >, >
Эти настройки отключают встроенный в VS Code линтер стилей, чтобы он не конфликтовал с stylelint и добавляют автоматическое исправление ошибок при сохранение файла. Для форматирования файла при нажатии клавиш shift+option+F , откройте файл keybindings.json из командной Command Pallete shift+command+P , и добавьте следующие настройки:
[ "key": "alt+shift+f", "command": "stylelint.executeAutofix", "when": "editorTextFocus && editorLangId == 'css'" >, "key": "alt+shift+f", "command": "stylelint.executeAutofix", "when": "editorTextFocus && editorLangId == 'scss'" >, "key": "alt+shift+f", "command": "stylelint.executeAutofix", "when": "editorTextFocus && editorLangId == 'less'" > ]
Настройки рабочей области будут доступны каждому разработчику при открытии проекта, а скачивать плагин stylelint и настраивать сочетание клавиш для своего VS Code, каждому разработчику нужно самостоятельно.
Команды для запуска
Для запуска линтинга всех файлов в проекте добавим новые скрипты в package.json :
"scripts": "stylelint": "stylelint '**/*'", "stylelint:fix": "stylelint '**/*' --fix" >
Команда npm run stylelint запустит линтер и выведет в консоль список ошибок, а npm run stylelint:fix дополнительно исправит ошибки, доступные для автоисправления.
Настраиваем Husky и lint-staged
Также настроим Git-хук на запуск линтера только для изменённых файлов при создании коммита. Для этого установим Husky и lint-staged:
npm i husky lint-staged --save-dev
И добавим настройки для этих плагинов в package.json :
"husky": "hooks": "pre-commit": "lint-staged" > >, "lint-staged": "*.(css|scss)": [ "stylelint --fix" ] >,
Заключение
Вот такая базовая настройка stylelint и VS Code поможет достичь большей консистентности кодовой базы и значительно сократит время на обсуждение форматирования стилей на код ревью. Посмотреть приложение с настроенным stylelint вы можете на Github.
vscode-stylelint
The official Visual Studio Code extension for Stylelint
Notice: 1.x of this extension has breaking changes from 0.x versions, including, but not limited to, changes to which documents are linted by default. See the migration section for more information.
Installation
- Execute the Extensions: Install Extensions command from the Command Palette.
- Type @id:stylelint.vscode-stylelint into the search form and install the topmost one.
The extension first looks for a copy of Stylelint installed in the open workspace folder, then for a globally installed version if it can’t find one. If neither can be found, it will not lint any documents.
Disable VS Code’s Built-In Linters (optional)
To prevent both VS Code’s built-in linters and Stylelint from reporting the same errors, you can disable the built-in linters in either the user or workspace settings for the languages you intend to use in your workspace.
An example of duplicate error messages emitted by both the built-in linter and vscode-stylelint.
For example, the following entries in .vscode/settings.json would disable the built-in CSS, Less, and SCSS linters:
Usage
Once you create a Stylelint configuration file or configure the Stylelint extension’s settings, Stylelint will automatically validate CSS and PostCSS documents (those with language identifiers css and postcss , respectively).
You can see or change the current document’s language in the bottom-right corner of the editor window.
Migrating from vscode-stylelint 0.x/Stylelint 13.x
⚠️ Stylelint 13.x and Prior is No Longer Supported
vscode-stylelint 1.x expects to use Stylelint 14 at minimum. Usage with prior versions of Stylelint is no longer supported. While older versions may continue to work for a while, you may encounter unexpected behaviour. You should upgrade your copy of Stylelint to version 14 or later for the best experience.
The syntax and configOverrides options have been removed from Stylelint 14 and this extension. See the following section for information on how to use different syntaxes.
⚠️ Stylelint is No Longer Bundled
Unlike 0.x, 1.x no longer provides a copy of Stylelint bundled with the extension. Bundling Stylelint brought up many unwanted side effects and significantly increased the extension’s size.
Starting with 1.x, vscode-stylelint will depend on having a copy of Stylelint installed in the open workspace (recommended) or globally (not recommended). If the extension doesn’t seem to be linting any documents, make sure you have Stylelint installed.
⚠️ Only CSS and PostCSS are Validated by Default
The 0.x versions of this extension, which used Stylelint 13.x and prior, supported validating many different languages out of the box without any additional configuration. However, this added a lot of complexity and resulted in many cases of unwanted or unexpected behaviour.
In current versions of the extension, the extension only supports validating CSS and PostCSS out of the box and requires additional configuration to validate other languages. You will need to:
- Install the PostCSS syntax for the language you want to validate into your workspace, e.g. postcss-scss.
- Configure Stylelint to use the syntax by providing the module name in the customSyntax option using overrides (or use the corresponding option in this extension’s settings). Example Stylelint config:
Extension Settings
Though relying on a Stylelint configuration file in your project is highly recommended, you can instead use the following extension settings:
stylelint.enable
Controls whether this extension is enabled or not.
stylelint.config
Sets the Stylelint config option. Note that when this option is enabled, Stylelint doesn’t load configuration files.
stylelint.configFile
Sets the Stylelint configFile option. Path to a JSON, YAML, or JS file that contains your configuration object. Use this option if you don’t want Stylelint to search for a configuration file.
stylelint.configBasedir
Sets the Stylelint configBasedir option. The path to the directory to which relative paths defining «extends» and «plugins» are relative. Only necessary if these values are relative paths.
stylelint.customSyntax
Sets the Stylelint customSyntax option, which points to a PostCSS syntax module. Must be either the package name or an absolute path to the module.
You can use $ to refer to the folder opened in VS Code.
stylelint.reportDescriptionlessDisables
Sets the Stylelint reportDescriptionlessDisables option. If true , Stylelint reports stylelint-disable comments without a description.
stylelint.ignoreDisables
Sets the Stylelint ignoreDisables option. If true , Stylelint ignores stylelint-disable (e.g. /* stylelint-disable block-no-empty */ ) comments.
stylelint.reportNeedlessDisables
Sets the Stylelint reportNeedlessDisables option. If true , Stylelint reports errors for stylelint-disable comments that are not blocking a lint warning.
stylelint.reportInvalidScopeDisables
Sets the Stylelint reportInvalidScopeDisables option. If true , Stylelint reports errors for stylelint-disable comments referring to rules that don’t exist within the configuration object.
stylelint.validate
An array of language identifiers specifying which files to validate.
stylelint.stylelintPath
Used to supply a custom path to the Stylelint module.
stylelint.packageManager
Controls the package manager to be used to resolve the Stylelint library. This setting only has an effect if the Stylelint library is resolved globally. Valid values are «npm» or «yarn» or «pnpm» .
stylelint.snippet
An array of language identifiers specifying which files to enable snippets for.
editor.codeActionsOnSave
This extension provides an action that you can use with VS Code’s editor.codeActionsOnSave setting. If provided a source.fixAll.stylelint property set to true , all auto-fixable Stylelint errors will be fixed on save.
The following turns on auto fix for all providers, not just Stylelint:
You can also selectively disable Stylelint:
You can also selectively enable and disable specific languages using VS Code’s language-scoped settings. For example, to disable codeActionsOnSave for HTML files, use the following:
Commands
This extension contributes the following commands to the command palette:
- Fix all auto-fixable problems : applies Stylelint resolutions to all automatically fixable problems.
Troubleshooting
vscode-stylelint writes logs to the VS Code output panel:
You can enable more verbose log output by running VS Code with the NODE_ENV environment variable set to development . You can do this on macOS and *nix by running:
And on Windows by running:
Contributors
Stylelint is maintained by volunteers. Without the code contributions from all these fantastic people, Stylelint would not exist. Become a contributor.
Sponsors
Thank you to all our sponsors! Become a sponsor.
Backers
Thank you to all our backers! Become a backer.
vscode-stylelint-plus
A Visual Studio Code extension to lint CSS/SCSS/Less with stylelint, support auto fix on save. Fork from vscode-stylelint.
Installation
- Execute Extensions: Install Extensions command from Command Palette.
- Type @sort:installs stylelint-plus into the search form and install the topmost one.
Optional (but recommended) setup
To prevent both the editor built-in linters [css] [less] [scss] and this extension [stylelint] from reporting essentially the same errors like in the screenshot, disable the built-in ones in User or Workspace setting:
Usage
Once a user follows the stylelint startup guide by creating a configuration file or by editing stylelint.* VSCode settings, stylelint automatically validates documents with these language identifiers:
- CSS ( css )
- HTML ( html )
- Less ( less )
- JavaScript ( javascript )
- JavaScript React ( javascriptreact )
- Markdown ( markdown )
- Markdown+MathML ( source.markdown.math )
- PostCSS ( postcss )
- Sass ( sass )
- SCSS ( scss )
- styled-components
- Official ( source.css.styled )
- Userland ( styled-css )
- Sugarss ( sugarss )
- Svelte ( svelte )
- TypeScript ( typescript )
- TypeScript React ( typescriptreact )
- Vue ( vue , vue-html , vue-postcss )
- XML ( xml )
- XSL ( xsl )
Extension settings
Though it’s highly recommended to add a stylelint configuration file to the current workspace folder instead, the following extension settings are also available.
stylelint.enable
Type: boolean Default: true
Control whether this extension is enabled or not.
stylelint.autoFixOnSave
Type: boolean Default: false
Turns auto fix on save on or off.
stylelint.configOverrides
stylelint.config
Set stylelint config option. Note that when this option is enabled, stylelint doesn’t load configuration files.
stylelint.useLocal
Type: Boolean Default: false
Use local version of stylelint.
stylelint.disableErrorMessage
Type: Boolean Default: true
Whether to turn off the display of error messages.