博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用PostCSS改善CSS的质量
阅读量:2508 次
发布时间:2019-05-11

本文共 15060 字,大约阅读时间需要 50 分钟。

The term “code quality” is not new to programmers. After all, every developer knows that it’s not enough for the code to just work. It should also possess other qualities: it should be readable, well formatted and consistent. It should also match a certain standard of quantitative metrics. Unfortunately, this is often overlooked when writing CSS. We can spend a lot of time debating why this happens, but the important part is that CSS is code as much as JavaScript, PHP or anything else, and we should pay attention to the way we write it. Otherwise, it may cause things to be more complicated than they should be.

术语“代码质量”对于程序员而言并不陌生。 毕竟,每个开发人员都知道仅仅使用代码还不够。 它也应该具有其他品质:应该可读,格式合理且一致。 它还应符合定量指标的特定标准。 不幸的是,这在编写CSS时经常被忽略。 我们可以花很多时间来讨论为什么会发生这种情况,但是重要的部分是CSS与JavaScript,PHP或其他任何东西一样都是代码,我们应该注意编写它的方式。 否则,它可能使事情变得比原本应该复杂的多。

In this article, we will explore how we can utilise PostCSS to help us maintain a higher quality in our CSS code. First, let’s try to pinpoint what we actually mean by “better CSS code”. There are several things to watch out for:

在本文中,我们将探讨如何利用PostCSS来帮助我们在CSS代码中保持更高的质量。 首先,让我们尝试指出“更好CSS代码”的实际含义。 有几件事情需要注意:

  • Code should be consistent in style – You are free to choose how you name your classes, where you place new lines or how you list the properties, but you should do it in the same manner across all of your stylesheets. Consistent style improves readability and makes the code easier to understand.

    代码的样式应该保持一致–您可以自由选择类的命名方式,新行的放置位置或属性的列出方式,但是您应该在所有样式表中以相同的方式进行选择。 一致的样式提高了可读性并使代码更易于理解。

  • Code should respect some metric standards – There are quantitative metrics that we can measure and keep at a certain threshold, such as the maximum precision of any selector or number of unique colours used on a page.

    代码应遵守某些度量标准–我们可以测量并保持一定阈值的定量度量,例如任何选择器的最大精度或页面上使用的唯一颜色的数量。

  • Hacks should be avoided – Certain constructs, such as, the !important directive may seem like a feasible solution at times, but they usually just make the code more complex.

    应避免黑客攻击某些构造(例如!important指令)有时似乎是可行的解决方案,但它们通常只会使代码变得更加复杂。

Certainly this is not a complete list, but let’s focus on the above problems for now. They might seem obvious, but they can be easily overlooked when working on a large project with a big team where people can vary in skill. What we would like is a tool that can help us enforce these standards automatically by means of code analysis. This is where PostCSS comes in.

当然,这不是一个完整的列表,但现在让我们集中讨论上述问题。 它们可能看起来很明显,但是当在一个大型团队中进行大型项目时,人们可以轻松地忽略它们,而这些团队的人员技能可能会有所不同。 我们想要一个可以帮助我们通过代码分析自动执行这些标准的工具。 这就是PostCSS出现的地方。

PostCSS如何提供帮助 (How Can PostCSS Help)

In the previous here at SitePoint, we covered what PostCSS is and how its plugins can be used for various purposes. In this article, we will focus on several PostCSS plugins that can help us keep our CSS code quality at its best.

在上的上 ,我们介绍了什么是PostCSS以及如何将其插件用于各种目的。 在本文中,我们将重点介绍几个PostCSS插件,这些插件可以帮助我们保持CSS代码质量的最佳状态。

Before we start, let’s set up a sandbox project we can experiment on. As opposed to using PostCSS via the command line as in the previous article, we’ll use Gulp instead. Start by creating a new folder and initiating an npm project there. After that we’ll need to install Gulp, the PostCSS plugin, and a for viewing the output of PostCSS plugins. To do that, navigate to the newly created project and run:

在开始之前,让我们建立一个沙盒项目以进行试验。 与上一篇文章中通过命令行使用PostCSS相反,我们将使用Gulp。 首先创建一个新文件夹并在那里启动一个npm项目。 之后,我们需要安装Gulp,PostCSS插件和一个以查看PostCSS插件的输出。 为此,请导航到新创建的项目并运行:

npm i gulp gulp-postcss postcss-reporter --save-dev

After that create an empty style.css file and a gulpfile.js with the following contents:

之后,创建一个空的style.css文件和一个具有以下内容的gulpfile.js

var gulp = require('gulp');gulp.task('analyze-css', function () {  var postcss = require('gulp-postcss');  var reporter = require('postcss-reporter');  return gulp.src('style.css')    .pipe(postcss([       reporter()    ]));});

This will define a task that will scan the contents of style.css and run it through a series of PostCSS plugins. You can already run gulp analyze-css but it won’t do much since there’s only a reporting plugin with nothing to report. Let’s add our first linting plugin.

这将定义一个任务,该任务将扫描style.css的内容并通过一系列PostCSS插件运行它。 您已经可以运行gulp analyze-css但不会做太多,因为只有一个报告插件,没有要报告的内容。 让我们添加第一个棉绒插件。

Stylelint (Stylelint)

By now there is surely a linter for any language and CSS is no exception. allows you to validate your CSS code against a predefined set of rules which can check your code for consistent formatting, usage of certain rules, units or directives, as well as potential mistakes (such as incorrect colors). It allows you to define — some of them do basic stuff, for instance, ensuring there is a space between a selector and the following curly brace, or that only single quotes are used. Others are more interesting. Here are a few examples:

到现在为止,肯定有一种适用于任何语言的lint,CSS也不例外。 允许您根据一组预定义的规则来验证CSS代码,这些规则可以检查代码的格式是否一致,某些规则,单位或指令的使用情况以及潜在的错误(例如错误的颜色)。 它允许您定义 -其中一些可以做一些基本的事情,例如,确保选择器和以下花括号之间没有空格,或者仅使用单引号。 其他人更有趣。 这里有一些例子:

  • property-blacklist and unit-blacklist allow you to specify a list of properties and units that cannot be used.

    property-blacklistunit-blacklist可让您指定无法使用的属性和单位的列表。

  • property-no-vendor-prefix warns you about using vendor prefixes for properties that don’t require them based on data from .

    property-no-vendor-prefix警告您有关根据数据为不需要的属性使用供应商前缀的信息。

  • declaration-no-important disallows using the !important directive.

    declaration-no-important禁止使用!important指令。

  • selector-max-specificity limits the maximum specificity of a selector.

    selector-max-specificity限制选择器的最大特异性。

Stylelint ships with all of the rules disabled by default, so you are expected to configure the rules yourselves. This can take a while, considering the amount of rules it has. Alternatively, you can use a predefined config such as and extend it with your own rules.

Stylelint出厂时默认禁用所有规则,因此您需要自行配置这些规则。 考虑到它的规则数量,这可能需要一段时间。 另外,您可以使用预定义的配置(例如 ,并使用自己的规则对其进行扩展。

Let’s set up stylelint with a standard rule set:

让我们用标准规则集设置stylelint:

npm i stylelint stylelint-config-standard --save-dev

You’ll also need to extend your gulpfile to enable the new plugin:

您还需要扩展gulpfile才能启用新插件:

var gulp = require('gulp');gulp.task('analyze-css', function () {  var postcss = require('gulp-postcss');  var stylelint = require('stylelint');  var reporter = require('postcss-reporter');  return gulp.src('style.css')    .pipe(postcss([      stylelint(),       reporter()    ]));});

Stylelint rules can be configured inline in the gulpfile, but I prefer to keep them in a separate file. Create a .stylelintrc file in your project folder and add the following contents:

可以在gulpfile中内联配置Stylelint规则,但我更喜欢将它们保留在单独的文件中。 在您的项目文件夹中创建一个.stylelintrc文件,并添加以下内容:

{  "extends": "stylelint-config-standard"}

This will tell stylelint that our own rule set will be based on the standard config. Now let’s update our style.css file and test the plugin against this savage piece of CSS:

这将告诉stylelint我们自己的规则集将基于标准配置。 现在,让我们更新我们的style.css文件,并针对这段野蛮CSS测试插件:

.title,.content{   background: #FFFFFF;   font-size:0.9em;  margin: 0;}

Just run gulp analyze-css and it will conveniently report a whole bunch of violations:

只需运行gulp analyze-css ,它将方便地报告大量违规情况:

style.css1:7  ⚠  Expected newline after "," (selector-list-comma-newline-after) [stylelint]1:15 ⚠  Expected single space before "{" (block-opening-brace-space-before) [stylelint]1:17 ⚠  Expected newline after "{" of a multi-line block (block-opening-brace-newline-after) [stylelint]1:17 ⚠  Unexpected whitespace at end of line (no-eol-whitespace) [stylelint]2:5  ⚠  Expected indentation of 2 spaces (indentation) [stylelint]2:17 ⚠  Expected "#FFFFFF" to be "#ffffff" (color-hex-case) [stylelint]2:17 ⚠  Expected "#FFFFFF" to be "#FFF" (color-hex-length) [stylelint]2:25 ⚠  Expected newline after ";" in a multi-line rule (declaration-block-semicolon-newline-after) [stylelint]2:25 ⚠  Unexpected whitespace at end of line (no-eol-whitespace) [stylelint]3:5  ⚠  Expected indentation of 2 spaces (indentation) [stylelint]3:15 ⚠  Expected single space after ":" with a single-line value (declaration-colon-space-after) [stylelint]4:4  ⚠  Unexpected whitespace at end of line (no-eol-whitespace) [stylelint]5:4  ⚠  Unexpected whitespace at end of line (no-eol-whitespace) [stylelint]6:5  ⚠  Expected indentation of 2 spaces (indentation) [stylelint]7:1  ⚠  Unexpected missing newline at end of file (no-missing-eof-newline) [stylelint]

Using this plugin can really help you enforce good practices when writing CSS. Continue by exploring the list of rules and overriding the ones from the standard config that you don’t agree with. You can later distribute these rules as your own set of your projects and teams. If there’s no rule that matches your need, you can always .

使用此插件确实可以帮助您在编写CSS时实施良好的做法。 继续浏览规则列表,并从您不同意的标准配置中覆盖这些规则。 您以后可以将这些规则作为您自己的项目和团队来分发。 如果没有满足您需求的规则,您总是可以 。

我用 (Do I Use)

A lot of pain when writing CSS comes from trying to keep in mind which browsers are you targeting and what features can be used in them. is a plugin that can help you make sure that the CSS you write is supported by your target browsers. You start by defining which browsers you are aiming to support. After that when you run the plugin, it will scan your code, validate it against the database of and trigger an error if some of the code is not supported.

编写CSS时,很多麻烦来自试图记住要定位的浏览器以及可以使用的功能。 是一个插件,可以帮助您确保目标浏览器支持您编写CSS。 首先定义要支持的浏览器。 之后,当您运行插件时,它将扫描您的代码,并针对的数据库进行验证,如果某些代码不受支持, 触发错误。

Using this plugin is fairly simple. Install it:

使用此插件非常简单。 安装它:

npm i doiuse --save-dev

And update your gulpfile:

并更新您的gulpfile:

return gulp.src('style.css')  .pipe(postcss([    doiuse({      browsers: ['ie >= 9', 'last 2 versions'],    }),    reporter()]));

This configuration says that we’re aiming to support the last 2 major versions of each browser, as well as IE9 and newer.

此配置表示我们的目标是支持每种浏览器的最后2个主要版本,以及IE9和更高版本。

To demonstrate the result, we’ll run the plugin on some fancy new CSS that uses features from the grid layout module.

为了演示结果,我们将在一些新颖CSS上运行该插件,该CSS使用网格布局模块中的功能。

body {  display: grid;  grid-columns: 200px 1% 1fr;  grid-rows: auto 15px auto 15px auto;}

Here’s what doiuse has to say about that:

这是doiuse必须说的:

style.css11:2    ⚠  CSS3 Multiple column layout not supported by: IE (9), Firefox (43,44), Chrome (48,49), Safari (8,9), Opera (34,35), iOS Safari (8.1-8.4,9.0-9.2) (multicolumn) [doiuse]

It’s a shame, but at the moment of writing, the CSS grid module is still not mature enough. But let’s focus on the good part: we now have a tool to help us keep up with tracking browser capabilities!

很遗憾,但是在撰写本文时,CSS网格模块还不够成熟。 但是,让我们专注于好的一面:我们现在有了一个工具来帮助我们跟上浏览器功能的跟踪!

不变CSS (Immutable CSS)

One of the major sources of bugs and complexities in stylesheets is overriding CSS rules. Even using the modern debug tools it sometimes may be challenging to figure out where the style was overridden and why. This is why it is considered good practice not to override styles but rather add additional modifiers to selectors. The plugin can warn you when such cases of style overriding occur in your code.

样式表中的错误和复杂性的主要来源之一是覆盖CSS规则。 即使使用现代的调试工具,有时也很难确定样式被覆盖的地方以及原因。 这就是为什么不覆盖样式而是在选择器中添加其他修饰符被认为是一种好习惯的原因。 当代码中发生样式覆盖的这种情况时, 插件会警告您。

It has two modes of operation. By default, it will only warn you if you try to override styles in different files. When multiple files are bundled into a single file, it will utilize source maps to figure out where the styles came from. This means it can play nicely with Sass imports or the plugin. If you want to take it a step further, you can enable strict mode, which will also warn you if you override styles in a single file.

它有两种操作模式。 默认情况下,仅当您尝试覆盖其他文件中的样式时,它才会警告您。 当多个文件捆绑到一个文件中时,它将利用源映射来找出样式的来源。 这意味着它可以与Sass导入或插件配合使用。 如果要更进一步,可以启用严格模式,如果您在单个文件中覆盖样式,则也会发出警告。

Here’s a quick example to demonstrate all of that. As usual, we’ll need to install the plugin first:

这是一个简单的示例来演示所有这些。 和往常一样,我们需要先安装插件:

npm i immutable-css --save-dev

And enable the plugin with strict mode in the gulpfile:

并在gulpfile中以严格模式启用插件:

return gulp.src('style.css')  .pipe(postcss([    immutableCss({      strict: true    }),    reporter()  ]))

Then feed it some nasty CSS:

然后提供一些讨厌CSS:

.title {  color: blue;  font-weight: bold;}.title {  color: green;}.article .title {  font-size: 1.2em;}

The plugin will conveniently report that the .title class has been mutated:

该插件将方便地报告.title类已被突变:

⚠  .title was mutated 3 times[line 1, col 1]: /Users/pavels/Documents/projects/sandbox/postcss/style.css[line 6, col 1]: /Users/pavels/Documents/projects/sandbox/postcss/style.css[line 10, col 1]: /Users/pavels/Documents/projects/sandbox/postcss/style.css

You can tinker around with the plugin in its .

您可以在其修改该插件。

CSS统计和列表选择器 (CSS Stats and List Selectors)

The last two plugins we’ll have a look at will be and . They are a bit different from the plugins we’ve examined so far: they don’t aim at pointing out problems but rather provide data for custom analysis.

我们将看看的最后两个插件是和 。 它们与到目前为止我们检查过的插件有些不同:它们的目的不是指出问题,而是提供用于自定义分析的数据。

CSS stats provides extensive information about the stylesheet in general: how many rules, selectors or declarations are used, what are they, what is the average specificity of a selector or what font sizes occur in the code. This is just a sample of the information that can be found in the generated report. A more detailed description can be found on . You can also visit for examples of reports that can be generated by using the data from the plugin.

CSS统计信息通常提供有关样式表的大量信息:使用了多少规则,选择器或声明,它们是什么,选择器的平均特殊性是什么,或代码中出现的字体大小。 这只是在生成的报告中可以找到的信息的一个示例。 可以在上找到更详细的描述。 您也可以访问以获得可以使用插件中的数据生成的报告示例。

List selectors is a simpler plugin that focuses on extracting the list of selectors used in the stylesheets and grouping them by categories — class selectors, attributes, IDs or tags.

列表选择器是一个更简单的插件,专注于提取样式表中使用的选择器列表,并按类别(类选择器,属性,ID或标签)对它们进行分组。

Both of these plugins can be used for all sorts of code analysis. Just a few examples are:

这两个插件都可以用于各种代码分析。 仅举几个例子:

  • Keeping your specificity, size and amount of used entities at a certain threshold.

    将您的特异性,使用的实体的大小和数量保持在某个阈值。
  • Making sure all of your selectors are written according to your coding style.

    确保所有选择器均根据您的编码样式编写。
  • Ensuring your media queries are consistent.

    确保媒体查询是一致的。

These are just some ideas that came to mind. A more practical approach would be to set up all of the previous plugins, return to these two and have a look to see if they can convey any more useful information.

这些只是想到的一些想法。 一种更实用的方法是设置所有先前的插件,返回到这两个插件,然后看看它们是否可以传达更多有用的信息。

包装全部 (Wrapping It All Up)

Code linting and analysis is just one of the ways one can use PostCSS, but it alone can add a lot of value to your development process, as well as save some time and a few grey hairs among your developers. Even though it’s becoming a common practice in other realms of programming it’s still frequently neglected when it comes to CSS. I believe that configuring PostCSS and these few plugins is a simple step to make your development much easier and more reliable.

代码整理和分析只是使用PostCSS的方法之一,但仅此一项就可以为您的开发过程增加很多价值,并为开发人员节省一些时间和一些麻烦。 尽管它已成为其他编程领域的普遍做法,但在CSS方面仍然经常被忽略。 我相信配置PostCSS和这几个插件是使您的开发更加轻松和可靠的简单步骤。

翻译自:

转载地址:http://burgb.baihongyu.com/

你可能感兴趣的文章
学习进度
查看>>
poj3368 RMQ
查看>>
“此人不存在”
查看>>
github.com加速节点
查看>>
解密zend-PHP凤凰源码程序
查看>>
python3 序列分片记录
查看>>
Atitit.git的存储结构and 追踪
查看>>
atitit 读书与获取知识资料的attilax的总结.docx
查看>>
B站 React教程笔记day2(3)React-Redux
查看>>
找了一个api管理工具
查看>>
C++——string类和标准模板库
查看>>
zt C++ list 类学习笔记
查看>>
git常用命令
查看>>
探讨和比较Java和_NET的序列化_Serialization_框架
查看>>
1、jQuery概述
查看>>
数组比较大小的几种方法及math是方法
查看>>
FTP站点建立 普通电脑版&&服务器版
查看>>
js 给一段代码,给出运行后的最终结果的一些综合情况、
查看>>
webservice 详解
查看>>
js自动补全实例
查看>>