linting
As front-end development has matured, the use of tools addressing code quality has grown substantially.
随着前端开发的成熟,解决代码质量的工具的使用已大大增加。
This is perhaps most evident when looking at the JavaScript ecosystem. Using a JavaScript linter is now the expected standard for front-end developers to ensure that their code is well structured and consistent. In fact, in my recent tooling survey, the vast majority of developers stated that they lint their JavaScript.
当查看JavaScript生态系统时,这可能是最明显的。 现在,对于前端开发人员来说,使用JavaScript linter是他们期望的标准,以确保他们的代码结构合理且一致。 实际上,在我最近的工具调查中, 绝大多数开发人员都表示他们对JavaScript轻描淡写 。
When it comes to writing CSS, the drive towards using code quality tools has been a little slower, with the majority of developers in that same survey stating that they chose not to use a CSS linter in their workflow.
在编写CSS时,使用代码质量工具的速度有些慢,该调查中的大多数开发人员都表示他们选择在工作流程中不使用CSS linter 。
![Stylelint Demo](https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/09/1505643410stylelint-demo.png)
I want to address this shortfall today, looking at one tool in particular that has raised the bar when it comes to linting stylesheets: stylelint.
我今天想解决这个不足,着眼于一个特别是在衬里样式表方面提高标准的工具: stylelint 。
It’s worth noting up front that although I reference CSS throughout this article, these references are interchangeable with a preprocessing language such as Sass. Stylelint can evaluate Sass and Less files as well as plain CSS and we’ll look at this in more detail later in the article.
值得注意的是,尽管我在本文中始终引用CSS,但是这些引用可以与预处理语言(例如Sass)互换。 Stylelint可以评估Sass和Less文件以及普通CSS,我们将在本文稍后详细讨论。
CSS Linting的简要历史 (A (Very) Brief History of CSS Linting)
When CSS linting was first introduced as a concept, it was fairly polarizing. Shortly after CSS Lint was introduced back in 2011, I remember reading an article by Matt Wilcox called CSS Lint is harmful, which criticized the opinionated nature of some of its rules – a sentiment that was shared by many in the community.
最初将CSS linting作为概念引入时,这是两极分化的。 CSS Lint在2011年推出后不久,我记得读过Matt Matt Cocox的文章CSS Lint是有害的 ,该文章批评了其某些规则的自以为是的态度–社区中的许多人都认同这种观点。
Looking back, CSS Lint was much like the first JavaScript linting tools that were available, such as JSLint – opinionated and not very flexible. However, while tools such as JSHint and ESLint emerged and pushed JavaScript linting forward, alternatives in the CSS linting landscape were non-existent.
回顾一下,CSS Lint就像是第一个可用JavaScript linting工具,例如JSLint-固执己见,并不十分灵活。 然而,虽然工具如JSHint和ESLint出现,并推动JavaScript的掉毛着在CSS掉毛景观的替代品是不存在的。
That is until stylelint arrived on the scene.
直到stylelint到达现场。
为什么选择Stylelint? (Why Stylelint?)
There are a few reasons why I think stylelint is now the best tool available when it comes to linting your CSS.
我认为stylelint现在是在整理CSS时可用的最佳工具有几个原因。
Firstly, it is completely un-opinionated. That means you can enable as few or as many rules as you like, with a number of its rules giving you options to configure them to your preferences.
首先,它是完全不受调理的。 这意味着您可以启用任意数量的规则,其中的许多规则为您提供了根据喜好配置它们的选项。
Also, it has a huge array of rules available – over 150 in fact, not including language specific rules for preprocessor specific syntax. Spending a little time to look through these is invaluable to building up a set of rules that fits how you write your styles.
此外,它还有大量可用的规则- 实际上超过150个 ,不包括针对预处理器特定语法的特定于语言的规则 。 花一点时间仔细阅读这些内容对于建立一套适合您编写样式的规则非常宝贵。
It is also very flexible, understanding CSS and CSS-like syntax such as SCSS and Less. So whether you want to lint preprocessor code or vanilla CSS, stylelint has you covered.
它也非常灵活,可以理解CSS和类似CSS的语法,例如SCSS和Less。 因此,无论您是希望整理预处理器代码还是使用普通CSS,stylelint都可以满足您的要求。
Lastly, and perhaps most importantly, its documentation is excellent. Want to see what rules are available? Check out the detailed documentation covering all available rules. How about some advice on how to contribute a new rule that you might like? They have a great developer guide to help you with that too.
最后,也许最重要的是,它的文档非常出色。 是否想查看可用的规则? 查看涵盖所有可用规则的详细文档 。 关于如何贡献您可能喜欢的新规则的一些建议怎么样? 他们也有出色的开发人员指南来帮助您实现这一目标。
Stylelint可以做什么? (What Can Stylelint Do?)
The value of adding a linting step when developing in any language is to improve the consistency of the code that you’re writing and to reduce the number of errors in your code.
在使用任何语言进行开发时,添加lint步骤的价值在于提高所编写代码的一致性并减少代码中的错误数量。
When applying this to CSS there are a number of issues that stylelint can help you address.
将其应用于CSS时,stylelint可以帮助您解决许多问题。
语法错误 (Syntax Errors)
Syntax errors are not subjective errors and should be very clear once highlighted.
语法错误不是主观错误,突出显示后应非常清楚。
Consider the following example:
考虑以下示例:
.element {
color: #EA12AE1;
disply: block;
}
The above code shows two different syntax errors. The first error is an invalid hex color. The second is a typo when declaring the display
property.
上面的代码显示了两种不同的语法错误。 第一个错误是无效的十六进制颜色。 第二个是声明display
属性时的错字。
These are pretty basic syntax errors that can get picked up by stylelint using rules such as color-no-invalid-hex
and property-no-unknown
, saving you the headache of having to find the mistake manually.
这些是相当基本的语法错误,stylelint可以使用诸如color-no-invalid-hex
和property-no-unknown
规则来识别,这使您省去了手动查找错误的麻烦。
格式和一致性 (Formatting and Consistency)
In CSS, code style preference can be extremely subjective. Chances are the way that I like to write my CSS isn’t the way that you prefer to write yours. It’s therefore important that a CSS linter can adapt to your preferences rather than trying to force a set of rules on you.
在CSS中,代码样式首选项可能非常主观。 我喜欢编写CSS的方式并不是您更喜欢编写CSS的方式。 因此,使CSS linter适应您的偏好而不是试图对您施加一组规则非常重要。
Consider the following styles:
考虑以下样式:
.listing {
display: block;
}
.listing-item
{
color:blue;
}
.listing-img{
width : 100%}
.listing-text { font-size: block; }
.listing-icon {
background-size: 0,
0; }
All of the rule sets above contain valid CSS, but they are clearly not consistent with one another in style. Use of spacing in each declaration is different and each block is formatted in a slightly different way.
上面的所有规则集都包含有效CSS,但是它们在样式上显然不一致。 每个声明中对空格的使用不同,并且每个块的格式略有不同。
This example shows just a few possible ways of formatting CSS. But in reality there are hundreds of subtle variations. Over a whole stylesheet (or multiple files), inconsistencies such as these can hinder the readability and maintainability of your code.
此示例仅显示了几种格式化CSS的可能方式。 但是实际上有数百种细微的变化。 在整个样式表(或多个文件)中,诸如此类的不一致会阻碍代码的可读性和可维护性。
This inconsistency becomes more apparent when a project is worked on by multiple developers, as each one might prefer to write their styles in a slightly different way. It’s always beneficial to get together and agree on a set of formatting rules that you will all stick to in such a situation.
当多个开发人员从事一个项目时,这种不一致会变得更加明显,因为每个开发人员可能都希望以略有不同的方式来编写其样式。 聚在一起并商定在这种情况下都会遵循的一组格式设置规则总是有益的。
Stylelint allows you to customize a set of rules to match the way that you, or your team, prefer to format your styles. Whatever preferences you have, stylelint can check that these rules are being applied consistently across your project.
Stylelint允许您自定义一组规则,以匹配您或您的团队偏好设置样式的方式。 无论您有什么首选项,stylelint都可以检查这些规则是否在您的项目中始终应用。
减少样式重复 (Reduce Duplication in Styles)
Duplication can be a pain to debug, whether it’s the duplication of selectors or properties in a stylesheet.
无论是选择器的复制还是样式表中的属性的复制,调试都可能很麻烦。
Take a look at the following CSS:
看一下以下CSS:
/* Property duplication */
a {
display: block;
color: orange;
font-size: 1.2rem;
display: inline; /* duplicate */
}
/* Selector duplication (1)
Same selector, at different points in stylesheet */
.foo {}
.bar {}
.foo {}
/* Selector duplication (2)
The same group of selectors, simply ordered differently */
.foo, .bar {}
.bar, .foo {}
Stylelint has several rules that can help spot this kind of duplication in your code, such as the declaration-block-no-duplicate-properties
rule that will catch duplicate properties.
Stylelint有几条规则可以帮助您在代码中发现这种重复,例如,clarification declaration-block-no-duplicate-properties
规则将捕获重复的属性。
It can also be configured to ignore intentional duplication, such as when the same property has been defined to provide a fallback value:
还可以将其配置为忽略有意的重复,例如在定义了相同属性以提供后备值时:
.example {
font-size: 14px;
font-size: 1.2rem; /* will override the above if browser supports rem */
}
最佳实践检查 (Best Practice Checks)
Best practices in CSS are somewhat subjective, but stylelint give you total flexibility in how you want to check for these “errors”, if at all.
CSS的最佳做法有些主观,但是stylelint使您可以完全灵活地检查这些“错误”(如果有的话)。
One commonly accepted best practice that falls into this category would be to throw an error when a certain selector nesting depth is exceeded when writing preprocessor code. This is useful to ensure that the specificity level of your styles is kept to a reasonable level and doesn’t get out of hand.
属于此类的一种公认的最佳实践是,在编写预处理程序代码时,如果超过某个选择器嵌套深度,则会引发错误。 这对于确保样式的特异性级别保持在合理水平并且不会失控非常有用。
Different developers and different use cases mean that what is deemed to be ‘acceptable’ may change from project to project. For example, you may have a legacy stylesheet in which you want to ensure the nesting depth doesn’t get any worse. The max-nesting-depth
rule lets you define your own acceptable nesting depth to check against, meaning that this rule could be useful for any project that uses a preprocessor.
不同的开发人员和不同的用例意味着被认为是“可接受的”项目可能会因项目而异。 例如,您可能要使用旧式样式表,以确保嵌套深度不会变差。 max-nesting-depth
规则使您可以定义自己可接受的嵌套深度以进行检查,这意味着该规则对于使用预处理器的任何项目都可能有用。
限制语言功能 (Limit Language Features)
The final set of checks that stylelint gives you access to is what they call ‘Limit language features’ in their rule guide. These can be used to enforce your own feature rules when working with your stylesheets.
stylelint提供给您的最后一组检查是规则指南中称为“限制语言功能”的内容。 在使用样式表时,这些可用于强制执行自己的功能规则。
A common example would be if you use a tool like Autoprefixer to automate adding vendor prefixes to your styles. In this scenario, it would be useful to throw a warning or an error if a vendor prefix has been manually added by a developer, as this will help to keep your code clean of unnecessary prefixes that will get added when the tool is subsequently run over unprefixed styles. Stylelint can take care of this for you with its ‘value-no-vendor-prefix’ rule rule, which does exactly that.
一个常见的例子是,如果您使用诸如Autoprefixer之类的工具来自动向样式添加供应商前缀。 在这种情况下,如果开发人员手动添加了供应商前缀,则发出警告或错误将很有用,因为这将有助于使代码避免不必要的前缀,这些不必要的前缀将在以后运行该工具时添加无前缀的样式。 Stylelint可以使用其“值无厂商前缀”规则规则为您解决此问题。
Other examples of rules range from disallowing named colors or specifying the maximum precision of numbers, to being able to blacklist certain properties if you so wish to.
规则的其他示例包括从禁止命名的颜色或指定数字的最大精度到您可以将某些属性列入黑名单 。
These rules are more opinionated by their very nature, but you can use them however you choose to. This means that your projects’ linting rules are tailored to how you and your team like to write your styles.
这些规则的性质更使人自以为是,但是您可以选择使用它们。 这意味着您的项目的整理规则是根据您和您的团队喜欢如何编写样式而定制的。
使用Stylelint (Using Stylelint)
We’ve covered what stylelint can do, but how easy is it to set up and use?
我们已经介绍了stylelint可以做什么,但是设置和使用它有多容易?
Like its rule set, stylelint is extremely flexible. There are a number of plugins available that make it easy to integrate into whichever build tool you prefer to use, as well as editor plugins for Atom, Sublime Text, and Visual Studio Code.
像其规则集一样,stylelint非常灵活。 有许多可用的插件 ,可以轻松地将它们集成到您更喜欢使用的任何构建工具中,以及Atom,Sublime Text和Visual Studio Code的编辑器插件 。
In terms of setting up your own rule set, there are multiple ways to do so. The easiest way is to create a .stylelintrc
file in your project’s root directory inside which you can start to build your own rules such as:
就设置自己的规则集而言,有多种方法可以做到 。 最简单的方法是在项目的根目录中创建一个.stylelintrc
文件,您可以在其中开始建立自己的规则,例如:
{
"rules": {
'block-closing-brace-newline-before': 'always-multi-line',
'block-closing-brace-space-before': 'always-single-line',
'color-no-invalid-hex': true,
'comment-no-empty': true,
'unit-case': 'lower',
'unit-no-unknown': true,
// etc...
}
}
When you then run your stylelint task – for example as part of your Gulp or webpack build – it will pick up the above configuration and use those rules to lint your styles.
然后,当您运行stylelint任务时(例如,作为Gulp或Webpack构建的一部分),它将选择上述配置并使用这些规则来整理样式。
Similar to JavaScript linting tools like ESLint, you can also use an existing configuration as a starting point and add your own rules. Stylelint has a recommended base configuration that you can extend, or you can choose to extend from more opinionated rule sets based on methodologies such as SUIT CSS.
与ESLint等JavaScript整理工具类似,您也可以将现有配置用作起点并添加自己的规则。 Stylelint具有建议的基本配置 ,您可以扩展该基本配置 ,也可以根据诸如SUIT CSS的方法从更多固执的规则集中选择扩展。
My advice would be to spend a little time looking through the available rules and creating a configuration that you and your team are happy with. Once proven useful, you could take the extra step of having your configuration available as an installable npm module – like the extendable rule sets mentioned above – so that you can then install and keep your stylelint configuration in sync across all of your projects.
我的建议是花一些时间查看可用的规则,并创建您和您的团队满意的配置。 一旦证明有用,您就可以采取额外的步骤,使配置作为可安装的npm模块可用(例如上述可扩展规则集),以便您可以在所有项目中安装并使stylelint配置保持同步。
整理预处理程序代码 (Linting Preprocessor Code)
As I mentioned earlier, stylelint can lint Sass or Less as easily as it can CSS.
正如我前面提到的,stylelint可以像CSS一样轻松地实现Sass或Less。
Setting this up depends on how you use stylelint. If you’re using a plugin for a build tool such as Gulp or webpack, you can pass through a value for stylelint’s syntax
option. This option takes less
or scss
as values depending on which syntax you wish to lint.
进行此设置取决于您如何使用stylelint。 如果您正在为Gulp或webpack等构建工具使用插件,则可以为stylelint的syntax
选项传递一个值。 根据您希望使用的语法, 此选项使用 less
或scss
作为值。
As an example, to specify that you would like to lint your .scss
files, you would pass the following object in as your stylelint options:
作为一个例子,指定你想你的皮棉.scss
文件,你会通过以下对象为您stylelint选项:
{
syntax: 'scss'
}
If you want to find out more on how you can use stylelint to lint preprocessor code, there’s a great section in its documentation dedicated to explaining just that.
如果您想了解更多有关如何使用stylelint整理预处理器代码的信息, 其文档中有很大一部分专门说明了这一点。
向前走,皮棉! (Go Forth and Lint!)
As you can see, stylelint has brought CSS linting a long way in a relatively short time. Its flexibility and breadth of rules means that you can set up a configuration that is as detailed or as hands off as you like, helping you to keep your styles more consistent, maintainable, and error free.
如您所见, stylelint在较短的时间内为CSS linting带来了长足的发展。 它的灵活性和规则广度意味着您可以根据需要设置尽可能详细或不复杂的配置,以帮助您保持样式更加一致,可维护且无错误。
It’s my hope that more developers choose to make use of such an excellent tool; so try taking it for a spin. Your stylesheets will thank you for it.
我希望更多的开发人员选择使用这种出色的工具。 所以尝试一下。 您的样式表将感谢您。
翻译自: https://www.sitepoint.com/taking-css-linting-next-level-stylelint/
linting