CSS linting with stylelint

Original author: David Clark
  • Transfer
Translation of David Clark's guest post on CSS-Tricks .

David is one of the creators of Stylelint , a tool to clean up CSS. He wrote an excellent introduction on why CSS is needed.

Stylelint hero


You are writing CSS. Perhaps a lot. And you make mistakes. Perhaps a lot too. The world needs a new hero who will save us from CSS errors!

Sometimes mistakes can have serious consequences. And sometimes this is just carelessly written or overly confusing 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 are messing with badly written code, and this makes them write strange things. The result is such that you could not even imagine in a nightmare.

Yes, you try to take care of yourself. Your colleagues support you and point out flaws. But we are all human, so you and your colleagues will someday miss a mistake. And, sometime in the future, you will encounter the consequences of those errors that show up in CSS.

Admit, in fact, no one, neither you, nor your colleagues, like to talk about your mistakes. This is somehow ridiculous. And some agreements (for example, on a single formatting of the code) would definitely help the case, but when it comes to manual corrections, they all seem too meticulous. Moreover, they may not demonstrate the best qualities of your colleagues when it comes to correcting trifles.

In addition, it would be much better to correct the work right away than to expect a code review that shows that you have duplicated some kind of announcement or should clean the indentation. An immediate response will help you quickly learn code writing conventions and spend less time pondering why CSS doesn't work.


The error recognizing mechanism is what we need.


We need a reliable, error-recognizing 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 own limitations. But these restrictions will be different from those that face you and your colleagues. He will prevent all errors that he can, and he will do it consistently and tirelessly. In the meantime, you can focus on improving the mechanism itself, increasing its capabilities and relaxing restrictions. If such a project is open, CSS developers from around the world will be able to contribute by sharing information about their mistakes.


CSS developers need linters, like everyone else


Programs that prevent errors are called "linters." There are already some good linters for Javascript. In particular, ESLint does wonders by showing us all how good a linter can be. But in the CSS world, everything was bad - we were limited by several options: the Ruby - written scss-lint preprocessor and the old CSS Lint .

But all this was before the advent of PostCSS . PostCSS, among other things, helps you create CSS-compatible tools for working with each other . It can parse any CSS-like syntax into the Abstract Syntax Tree (AST, Abstract Syntax Tree - approx. Translator ), with which the plug-ins work in the future. With helpspecial parsers PostCSS can handle even non-standard, technically “invalid” templates (for example, comments through //).

Thus, the ground has ripened for a new powerful CSS linter - 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 you to what we 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 huge opportunities for expansion.

If you already feel growing impatience (“Good, good, I already believed that stylelint is incredible. No need to crush water in a mortar!”), Just skip this section. In the following, I will answer frequently asked questions and give some tips.


1. Finding mistakes


Some Stylelint rules are designed to detect obvious errors: typos or descriptions made when you were in a hurry or were inattentive. For example, you can forbid empty blocks in the code, incorrect hex values, duplicate selectors, undeclared animations, incorrect syntax of linear gradients.

Other rules are designed to catch more complex errors. For example, there is a rule that fires when you use a shortened property spelling (for example, margin) that 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 this situation: imagine that Rule A is before Rule B, however, it rewrites Rule B, since the selector of Rule A is more specific (for example, Rule A is declared in .foo.bar {...}, and Rule B in .foo {...}). This is not khukh-mukhra for you.

Another rule uses the doiuse PostCSS plugin , checking if your styles will work for all browsers that you decide to support. Another rule uses css-colorguardto compare the colors used in the project, and ask you whether to 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 other PostCSS plugins).


2. Impose best practices


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

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

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

If you want something more serious, devote some time to the 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 a style of writing code


Stylelint has a bunch of rules that automatically impose conventions on the style of the code, so neither you nor your colleagues should do this. We tried to make these rules as complete and incredibly flexible as possible .

Most of these rules are indented. However, there are those that check the types of quotes, setting uppercase and lowercase characters, substituting zero in fractional values, using abbreviated / full rules, etc.

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


4. Customize and expand anything


Nicholas Zakas, creator of ESLint (and also CSS Lint), wrote that the secret to ESLint's success is its extensibility. Stylelint follows the lead of ESLint and strives to be as extensible as possible.

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

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

If you don’t like the built-in output tools in stylelint, you can create your own, and even adapt them for your organization. You can also configure alerts 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 you can use stylelint, let us know!


Answers to frequently asked questions


Somewhere in the bowels of your consciousness, questions must have already appeared. Here are the answers to the most frequent ones that we are usually asked:


Can I use stylelint with SCSS or Less?


Yes, you can use stylelint with SCSS! And more recently, Less has appeared. 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 stylelint.

Currently 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 for it!

Stylelint tries to cover all possible spellings: some people use standard CSS syntax, others use extensions like SCSS, and others use strange special properties. Of course, some rules can break if you use non-standard 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 file-by-line, and line by line.


Can I use stylelint with future CSS syntax?


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


The stylelint configuration can be huge. What is the best place to start?


We recommend creating a configuration in one of three ways:

  • You can take an already published configuration and expand it. We have created and maintain stylelint-config-standard , as a basis suitable for most users. And you can find quite a few other configurations.
  • Start from scratch and add one rule at a time. Initially, all rules are turned off, so by adding one rule after another, you know exactly what each one does. You will understand each of your rules and be able to configure them.
  • Copy the starting configuration and decide which options to use and which rules to remove.

Fortunately, you do not have to write huge stylelint configurations over and over again. 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. A plugin for Grunt has recently appeared ( approx. Translator, thanks for clarifying vz2oo5 ). We hope they inspire people to develop plugins for other task managers as well.

You can also use 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, plugins for Atom, Sublime Text, and VS Code text editors already exist that provide faster responses to your code. All of this is compiled on our Complementary Tools page .

Here's what it might look like on the command line:

Stylelint in CLI


And here it looks in Atom:

stylelint in atom


Will stylelint fix my mistakes?


No, but there is another project called stylefmt for this . It takes a stylelint configuration — exactly the same as yours — and fixes anything it can fix. We hope that with the help of the community, stylefmt will grow so much that it can fix all violations that can be fixed automatically. Help him achieve this!

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


Discipline yourself with linting


There are an incredible amount of CSS spelling rules. We all know that it is 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 that you will wrinkle from in a week.

The ambitious goal of stylelint is to automate the rules for writing code. This will create a framework of rules and infrastructure that CSS developers will be able to implement in order to improve their own practices.

Try stylelint and tell us about your experiences. If you have ideas for improving it - go ahead! Complement our code with rules, extensions, tests, bug fixes, documentation, new ideas, or just feedback. We always have a job for developers of any level.

Also popular now: