When you write a lot of CSS code, more than one error may occur. You may need a tool to prevent your CSS writing errors.
Maybe, sometimes your error is really a bug. Or it could just be inconsistency or unclear coding style due to sloppiness. Maybe many of them may seem trivial (depending on your temperament), but as the code base grows and over time, many people will make ugly things when using them. The consequences of the matter are beyond your imagination.
You try to control yourself. Your colleagues also help you and promptly correct your mistakes when you wander. However, you and your colleagues are the makers of mistakes, so failure is inevitable in the end, at least to some extent. Later, you or someone else will have to fix the problem caused by the CSS error on your page.
Neither you nor your colleagues like to discuss your mistakes because they are embarrassing. It can even be frustrating or emotionally damaging at times. Certain disciplines are sometimes helpful in maintaining a code base, such as a consistent writing style, which may seem a bit pedantic and boring when implemented manually. Otherwise they will bring out the pushy, stubborn elements you usually like.
In addition, you may prefer to be able to correct errors in time, rather than waiting for someone else to point out the error after the code review, then make the modification yourself and declare that you will not make such errors again. When there is an error in your CSS, a timely feedback will help you save a lot of time.
What you need is a machine that prevents errors
You need a bug-proof machine that understands CSS and understands you: your intentions, preferences, ideas, and weaknesses.
This machine will have limitations. All things are not perfect. But this limitation is different for you and your colleagues. As long as it can prevent errors, it will continue to prevent them, tirelessly. Meanwhile, you and your colleagues can always improve the machine, extending its capabilities and weakening its limitations. It's open source, and people around the world can join in and do their part - other authors who want to stop themselves from making CSS writing errors.
Like everything else, CSS authors need linters
We call these programs that prevent errors "linters". There are several better linters in Javascript. ESLint, in particular, works like a miracle and shows us how useful a good linter can be. But in CSS, we are not so lucky, and our options are very limited: Ruby-based scss-lint with a special preprocessor and the older CSS Lint.
But this was before PostCSS. In addition, PostCSS provides some methods to build more interactive CSS tools. It can parse any CSS-like syntax into an abstract syntax tree (AST) plug-in for analysis and operation. And with custom parsers, PostCSS can even handle non-standard invalid patterns (such as //
comments)
The conditions are ripe to produce a linter with more powerful features - based on the power of PostCSS and inspired by the best features of scss-lint and ESLint.
I am working on this project with several friends, and now I will start to introduce the tool we developed: stylelint.
Things you can do with stylelint
The following is a summary of the functions tried in stylelint, which has more than a hundred rules and is scalable.
At this point, if you find yourself getting a little impatient ("Ok, Ok: I believe stylelint will work wonders. No need to summarize."). Just skip to the next section, where I'll just address some issues and provide some tips.
Error catching
Some stylelint rules are designed to catch obvious errors, such as misspellings or omissions made when you were distracted or bleary-eyed. For example, you can suppress empty blocks, invalid hex values, duplicate selectors, unnamed animation names and incorrect linear gradient syntax.
The other rules are all about trying your best to catch more subtle errors. Here's a rule: give a warning when you use a shorthand attribute (like margin-top
) that overrides its attribute counterpart (like margin
), as this may be due to oversight on your part. In addition, there is also a rule that will warn you: when a confusing situation occurs, such as rule A appearing before rule B, but actually overriding rule B because the selector of rule A has a higher priority (for example, rule A is .foo.bar{···}
, rule B is .foo{···}
). This is a very tricky situation.
There is also a rule that uses the douse plug-in of PostCSS to check whether your browser supports this style. The other one uses the css-colorguard plug-in to prompt the similarity of colors to avoid confusing you. (Please note: This is one of the main advantages of stylelint on top of PostCSS: stylelint can prompt with very little effort compared to other PostCSS plugins.)
Enforce best practices
If you use system methods in your stylesheets, or set a style guide for your code, you should disable these patterns. stylelint already provides these functions.
First, you need to have tight control over your selectors. Using stylelint, you can disable selectors beyond a certain specificity or set limits on nesting depth. You can suppress category selectors (e.g. selectors without ids) and use regular expression naming conventions for the remaining selectors.
You can disable the use of !important
or browser hacks that your browser does not support. If you use Autoprefixer (or you should), you can disable the use of vendor prefixes in source stylesheets.
If you want to be more rigorous - you can spend some time on the configuration to ensure absolute consistency - you can enforce the ordering of stylesheet properties and provide properties, values for blacklist, whitelist, Functions also have units.
Enforce code style conventions
stylelint automatically enforces code style conventions so you and your teammates don’t have to actively set them up. We are committed to making these rules more comprehensive and flexible.
These rules mainly focus on whitespace, but also apply to other details, such as quotation marks, upper and lower case letters, writing zeros before decimals, using keywords and spelling out values, etc.
Dream that you and your teammates can establish a formatting convention (e.g. we always leave a space after a colon in a declaration) and change it in your stylelint configuration, and you won't have to discuss it again. Let it be executed in the machine kingdom.
Make and expand everything
Nicholas Zakas, the creator of ESLint (and CSS Lint), writes that the success of ESLint lies in its extensibility. stylelint attempts to follow ESLint's lead and provide CSS authors with a linter that is also extensible.
You can write and publish your own rule plugins. There are a bunch of them available now; and we're eager to see other people's great plugins.
Configurations are extensible and therefore can be shared. As for plug-ins, we learned the value of this feature from ESLint. Check which includes WordPress and SUITCSS configurations and published ones.
If you don’t like stylelint’s built-in hints, you can hand-create your own styles, even for your organization. You can also customize the rules used to provide warning messages.
Using the stylelint API, you can create text compiler plug-ins and test them to integrate stylelint into every aspect of your workflow.
If you have ideas for stylelint extensions, please let us know!
Answers to expected questions
There may be several questions in your mind. Here are some explanations for the most common questions:
Is it possible to use stylelint in SCSS or Less?
The answer is yes, you can use stylelint in SCSS and it is supported in Less! Since PostCSS allows custom parsers, stylelint can easily support a variety of non-standard syntaxes - you can customize a PostCSS parser to parse them.
Because of the PostCSS parser -- stylelint supports SCSS, Less and the new SugarSS. If you want to implement another custom syntax support, you can achieve it through PostLess!
Of course, there are certain rules to get in the way of your non-standard syntax (such as the #{$interpolation}
that confuses Sass id selectors). Because stylelint tries to mask the styling of our stylesheets - some people use standard CSS, some people use extended languages like SCSS, some people use some weird custom properties, etc. - these inevitably create some holes that need to be filled. However, we are constantly working on these bugs as we find them; any rules in the meantime can be turned off completely or disabled on a stylesheet-by-stylesheet or line-by-line basis.
Can stylelint use future CSS syntax?
Yes! Similar to the answer stated above: stylelint can understand anything PostCSS understands, including enabling any future CSS syntax (possibly via PostCSS plugins). In fact, some stylelint rules specifically handle future CSS syntax and some custom properties.
The stylelint configuration is huge, where do I start?
We recommend three configuration methods:
Extend a published configuration. We maintain stylelint-configuration standards in order to provide users with a consistent baseline. And many configurations have also been announced. Start from scratch and add one rule at a time. By default, none of the rules are enabled, so by adding rules manually you will know which ones will be enforced and understand each rule you add. Enable copy-paste configuration, decide which options to use and selectively remove them.
Thankfully, you don’t need to write huge stylelint configuration over and over again. You can choose a style you like and use it anywhere.
Easiest way to run stylelint?
For most people, the easiest way is through its command line.
gulp プラグインを使用したい場合は、gulp-stylelint を使用できます。 Webpack に関しては、選択できるオプションが多数あります。これらのプラグインが、Grunt などの他の stylelint プラグインを作成するきっかけになることを願っています。 (オープンソース プロジェクトで見つけることができます!)
PostCSS プラグイン (プラグインに含まれるものを含む) を使用して stylelint を実行することもできます。これは、PostCSS (ほぼすべてのコンパイル ツールをカバーします) を使用できる場所ならどこでも stylelint を使用できることを意味します。
さらに、最速のフィードバックを提供する、Atom、Sublime Text、VS Code 用の stylelint テキスト コンパイル プラグインもあります。詳細については、stylelint Web サイトの補完ツールのリストを確認してください。
以下に示すように、コマンドラインで表示されると予想される結果は次のとおりです。
は Atom
では次のように表示されます。stylelint でエラーを修正できますか?
いいえ、しかし、stylefmt と呼ばれる別のツールはまさにそれを目的としています。これは、lint に使用するものと非常によく似た stylelint 設定を使用し、あらゆるエラーを修正できます。コミュニティからの貢献により、stylelint が stylelint ルールに違反するバグに自動的にパッチを適用できるように進化できることを願っています。彼らがこの目標を達成できるよう支援してください。
CSScomb や、stylelint と組み合わせた Perfectionlist などの他のツールを使用して、自動的に中断を修正したり強制的に中断したりすることもできます。
制約の補足に lint を使用する
優れた CSS には膨大な量の制約があります。そのため、私たちは SMACSS、ACSS、BEM、SUITCSS、ITCSS などの手法について議論することに多くの時間を費やしています。不適切な CSS を書くのがいかに簡単かは誰もが知っているので、CSS スタイルを書くことを恐れなくなったら、仕事において賢明な戦略を確立し、勇敢にそれに固執する必要があります。
stylelint の目標は、実行を自動化することです。CSS 作成者が独自の戦略を実装するために使用できる、ルールのコア セットとプラグイン可能なフレームワークを提供します。
試してみて、どのように機能するかをお知らせください。貢献ルール、機能強化、テスト、バグ修正、ドキュメント、新しいアイデア、または単なるフィードバックなど、より良い改善のためのアイデアをお持ちの場合は、ぜひご連絡ください。これにより、あらゆるレベルの開発者にやるべきことが与えられます。