📜 ⬆️ ⬇️

Lint CSS using stylelint

Translation of David Clarke's guest post to CSS Tricks .

David - one of the creators of Stylelint - a tool to clean up the CSS. He wrote an excellent introduction on why CSS should be injected.

Stylelint hero
')

You write CSS. Perhaps a lot. And you make mistakes. Perhaps too much. The world needs a new hero who will save us from mistakes in CSS!

Sometimes mistakes can have serious consequences. And sometimes it’s just a carelessly written or overly complicated code. Some of the typos at first seem insignificant (which, of course, depends on your temperament), but the further the project grows, the more serious they become. More and more people dirty their hands about badly written code, and this causes them to write weird things. The result is such that you could not even imagine in a nightmare.

Yes, you try to look after yourself. Your colleagues support you and point out flaws. But we are all human, so you and your colleagues will ever miss a mistake. And, sometime in the future, you will encounter the consequences of the mistakes that are found in CSS.

Admit, in fact, no one, neither you nor your colleagues, like to talk about your mistakes. It's kind of ridiculous. And some agreements (for example, on uniform formatting of the code) would definitely help the cause, but when it comes to manual fixes, they all seem too meticulous. Moreover, they can demonstrate not the best qualities of your colleagues when it comes to correcting small things.

On top of that, it would be much better to correct the work right away than to expect a code-review, in which it turns out that you duplicated some kind of announcement or should clean the indents. Immediate reaction will help you quickly grasp the code writing arrangements and spend less time wondering why CSS is not working.


The error-detecting mechanism is what we need.


We need a reliable, error-detecting mechanism that understands CSS and understands us: our intentions, preferences, ideals, and weaknesses.

Of course, like all such things, such a mechanism will have its limitations. But these restrictions will be different from those facing you and your colleagues. It will prevent all errors that it can, and will do so consistently and tirelessly. In the meantime, you can focus on improving the mechanism itself, increasing its capabilities and easing restrictions. If such a project is open, CSS developers from all over the world will be able to contribute by sharing information about their mistakes.


CSS developers need linters like everyone else.


Error prevention programs are called “linders”. For Javascript, there are already some good linters. In particular, ESLint simply works wonders, showing all of us how good a linker can be. But in the CSS world everything was bad - we were limited to several options: the Rubss preprocessor scss-lint and the old CSS Lint written in Ruby.

But all this was before the arrival of PostCSS . PostCSS, among other things, helps you create compatible CSS tools . It can parse any CSS-like syntax into Abstract Syntax Tree (AST, Abstract Syntax Tree - comment of the translator ), which the plug-ins work on with. With the help of special parsers, PostCSS can even process non-standard, technically "non-valid" templates (for example, comments via // ).

Thus, the ground for a new powerful CSS linter has been ripe - based on PostCSS and incorporating the best aspects of scss-lint and ESLint.

In this project, I worked with several colleagues, and now I want to introduce to you what we have created - stylelint .


A few things you can do with stylelint


What is written below is an attempt to summarize the possibilities of stylelint. It contains more than a hundred rules and great opportunities for expansion.

If you already feel a growing impatience ("Well, well, I already believed that the stylelint is incredible. Do not push the water in a mortar!"), Just skip this section. In the following I will answer frequently asked questions and give a few hints.


1. Find errors


Some of the Stylelint rules are used to detect obvious mistakes: typos or typographical errors made when you were in a hurry or were inattentive. For example, you can disable empty blocks in code, invalid hex values, duplicate selectors, undeclared animations, and incorrect linear gradient syntax.

Other rules are designed to catch more complex errors. For example, there is a rule that works when you use abbreviated property writing (for example, margin ), which overlaps one of its expanded options (for example, margin-top ), although you most likely did not want this. And there is also a rule that works in such a situation: imagine that Rule A is before Rule B, but overwrites Rule B, since the selector for Rule A is more specific (for example, Rule A is announced in .foo.bar {...} , and Rule B in .foo {...} ). This is not a huhra-mukhra.

Another rule uses the doiuse PostCSS plugin to check if your styles will work for all browsers that you decide to support. Another rule uses css-colorguard to compare the colors used in the project, and to ask you whether you should use a single color instead of several similar ones. (Have you already noticed that stylelint uses one of the main advantages of PostCSS? It's quite simple to make rules that use the results of the work of other PostCSS plug-ins).


2. To impose best practices


If you follow a certain methodology when working with styles or have a specific code style, you should be able to not accept some code constructs. Stylelint provides you with such features.

Moreover, you need to control your selectors. Mercilessly Using stylelint, you can prohibit selectors that exceed the specified specificity, or, finally, put an end to the deep nesting of selectors. You can prohibit the use of certain categories of selectors (for example, id) and create regular expressions that check that selectors follow naming conventions.

You can prohibit the use of !important or browser hacks that are not related to the browsers that you support. If you use Auto Prefix (which you probably should do), you can prohibit the use of browser prefixes in the source files.

If you want something more serious, devote some time to settings, and you can set the order of properties in your rules, create black and white lists of rules, values, functions and units of measure.


3. To impose code writing style


In stylelint there are a lot of rules that automatically impose agreements on the style of code, so neither you nor your colleagues should deal with this. We tried to make these rules as complete as possible and incredibly flexible .

Most of these rules are related to indents. However, there are those that check the types of quotes, the setting of uppercase and lowercase characters, the substitution of zero in fractional values, the use of abbreviated / full rules, etc.

The idea is that you and your colleagues can agree on the style of the code once (for example, “And let's always put a space after the colon in the rule declarations”), put it in the stylelint configuration and not remember it again. Let the machines suffer for you!


4. Customize and expand anything


Nicholas Zakas, creator of ESLint (and also CSS Lint), wrote that the secret of success of ESLint is in its extensibility. Stylelint follows the example of ESLint and tries to be as expandable as possible.

You can write and publish your own rules as plugins. A certain amount is already available, and we cannot wait to find out what else the community will come up with.

Configurations can be expanded, and therefore they can be shared. We adopted this from ESLint, just like the plugins. Here you can see already published configurations, and among others - configurations from WordPress and SUITCSS.

If you don’t like the inline style output tools, you can create your own, and even customize them for your organization. You can also customize the notifications displayed by the rules.

Using the stylelint API, you can create plugins for text editors and task managers that embed stylelint in every step of the workflow.

And, if it comes to your mind, how else can you use stylelint, let us know!


Answers to frequently asked questions


Somewhere in the depths of your mind, there must have already been questions. Here are the answers to the most frequent ones that we usually ask:


Can I use stylelint with SCSS or Less?


Yes, you can use stylelint with SCSS! And just recently there was support for Less. Since PostCSS allows you to use special parsers , stylelint has no problems with non-standard syntax - everything for which you can write a PostCSS parser can be run through the stylelint.

At the moment there are the following PostCSS parsers - and, therefore, stylelint support - SCSS , Less , the new SugarSS . If you want to support a different special syntax, help with writing a PostCSS parser to it!

Stylelint tries to cover all possible spellings: some people use standard CSS syntax, others - extensions, like SCSS, and still others - strange special features. Of course, some rules can break if you use a nonstandard syntax (for example, #{$interpolation} from Sass and the rule about id in selectors). Of course, when we find such errors, we deal with them. But, nevertheless, you yourself can turn off any rule, both completely and per file, and line by line.


Can I use stylelint with future CSS syntax?


Yes! As in the answer above: stylelint can parse everything that PostCSS understands, including future CSS syntax (which you most likely use with PostCSS plug-ins). Honestly, some of the stylelint rules are aimed at future CSS, such as range and custom properties .


The stylelint configuration can be huge. Where better to start?


We recommend creating a configuration in one of three ways:


Fortunately, you do not have to write huge stylelint-configuration time after time. Create one that meets all your requirements, and use it everywhere.


What is the easiest way to use stylelint?


The easiest way to use stylelint is through its CLI .

If you prefer a gulp plugin, there is gulp-stylelint for you. There is also an option for webpack. Recently there was a plugin for Grunt ( approx. Translator, thanks for clarifying vz2oo5 ). We hope that they will inspire people to develop plugins for other task managers.

You can also use the stylelint as a PostCSS plugin, including it in any plugin chain. In other words, you can use stylelint wherever PostCSS can be run — that is, in almost any build tool!

In addition, there are already plug-ins for text editors Atom, Sublime Text and VS Code, providing a faster response to your code. All this is collected on our Complementary Tools page.

Here’s how it might look on the command line:

Stylelint in CLI


And this is how it looks in Atom:

stylelint in atom


Will stylelint correct my mistakes?


No, but for this there is another project called stylefmt . He takes the configuration stylelint - exactly the same as yours - and fixes everything he can fix. We hope that with the help of the community stylefmt will grow so much that it will be able to correct all violations that can be corrected automatically. Help him achieve it!

In addition, you can use other tools along with stylelint, such as CSScomb or perfectionist (or postcss-sorting , note translator ), automatically correcting one and showing the other.


Discipline yourself with linting


There are an incredible amount of rules for writing CSS. We all know that it's very easy to write bad CSS, which is why we spend so much time talking about methodologies (SMACSS, ACSS, BEM, SUITCSS, etc.). You must choose a strategy and stick to it. Unless, of course, you want to write code from which you will frown in a week.

The ambitious goal of stylelint is to automate the rules of writing code. This will create some kind of a backbone of rules and infrastructure that CSS developers can implement in their work to improve their own practices.

Try stylelint and tell us about your impressions. If you have ideas on how to improve it - go ahead! Add our code with rules, extensions, tests, bugfixes, documentation, new ideas, or just feedback. We always have a job for developers of any level.

Source: https://habr.com/ru/post/301594/


All Articles