postcss

tech2022-12-22  115

postcss

Most developers who spend their time working with CSS are familiar with preprocessors such Less, Sass, and Stylus. These tools have become a vital part of the web development ecosystem. Writing styles for a website without using features like nesting, variables, or mixins now seems cumbersome and awkward. Although each of them is a great and extremely useful product, let’s take a step back and consider if using preprocessors in such a way is indeed the best approach.

花费大量时间使用CSS的大多数开发人员都熟悉Less,Sass和Stylus等预处理器。 这些工具已成为Web开发生态系统的重要组成部分。 现在,不使用嵌套,变量或混合功能之类的网站来编写样式似乎很麻烦和尴尬。 尽管它们中的每一个都是一个出色且非常有用的产品,但让我们退后一步,考虑一下以这种方式使用预处理器是否确实是最好的方法。

I see a couple of problems with tradition preprocessors:

我看到传统预处理器有两个问题:

They are not extendable. Whichever preprocessor you choose, you are limited to the set of features that it provides. If you need anything on top of that, you’ll need to add it as a separate step in your build process. If you feel like writing your own extension, you’re on your own.

它们是不可扩展的。 无论选择哪种预处理器,都只能使用它提供的功能集。 如果除此之外还需要其他任何内容,则需要在构建过程中将其作为单独的步骤添加。 如果您想编写自己的扩展程序,那您就一个人了。

You can’t leave anything out. Some of the features preprocessors provide such as Sass’s @extend may be detrimental to you, and you might want to leave them out completely. Unfortunately, while you can avoid using them, you can’t remove that part of the tool to minimize code.

你不能遗漏任何东西。 预处理器提供的某些功能(例如Sass的@extend 可能对您不利 ,您可能希望将其完全排除在外。 不幸的是,尽管可以避免使用它们,但不能删除该工具的那部分以最小化代码。

They push out CSS standards. You might say that each of the preprocessors has become a standard of its own. Regrettably, they don’t aim at being compatible with the W3C standards, which means that they cannot be used as polyfills for early testing of the newer W3C standards.

他们推出CSS标准。 您可能会说每个预处理器都已成为其自己的标准。 遗憾的是,它们并不旨在与W3C标准兼容,这意味着它们不能用作新W3C标准的早期测试的填充料。

This is where PostCSS comes in.

这就是PostCSS出现的地方。

什么是PostCSS? (What is PostCSS?)

PostCSS is not a preprocessor per se; it doesn’t transform CSS. As a matter of fact, it doesn’t do much by itself at all. What it does is provide a CSS parser and a framework for creating plugins that can analyse, lint, handle assets, optimise, create fallbacks, and otherwise transform parsed CSS. PostCSS parses CSS into an abstract syntax tree (AST), passes it through a series of plugins, and then concatenates back into a string. If you’re familiar with JavaScript tooling, then you can think of PostCSS as Babel for CSS.

PostCSS本身不是预处理器。 它不会转换CSS。 事实上,它本身并没有做太多事情。 它的作用是提供CSS解析器和用于创建插件的框架,这些插件可以分析,处理,处理资产,优化,创建后备以及转换已解析CSS。 PostCSS将CSS解析为抽象语法树(AST),将其通过一系列插件传递,然后串联回字符串。 如果您熟悉JavaScript工具,那么可以将PostCSS视为CSS的Babel 。

There are currently more than 200 plugins for PostCSS, many of which are listed on the PostCSS GitHub page, while others can be found on the useful PostCSS directory postcss.parts. PostCSS can be integrated in most the build tools including Gulp, Grunt, webpack or npm.

当前,有超过200个PostCSS插件,其中许多列在PostCSS GitHub页面上 ,而其他插件可在有用的PostCSS目录postcss.parts中找到 。 PostCSS可以集成到大多数构建工具中,包括Gulp,Grunt,webpack或npm。

So how does PostCSS tackle the problems we listed earlier?

那么PostCSS如何解决我们前面列出的问题?

Each plugin is installed separately. This means you choose which ones you need and in what order they should be applied. Usually, plugins can be additionally configured using some set of options.

每个插件都单独安装。 这意味着您可以选择所需的内容以及应采用的顺序。 通常,可以使用一些选项来额外配置插件。

You can write your own plugins. Each PostCSS plugin receives parsed CSS as an input parameter, analyses or modifies it, and returns it in the same manner. This means that plugins don’t need to handle parsing CSS and converting it back into a string. So the ability to build your own plugins is not as difficult as you might think.

您可以编写自己的插件。 每个PostCSS插件都将解析后CSS作为输入参数,对其进行分析或修改,然后以相同的方式返回。 这意味着插件无需处理解析CSS并将其转换回字符串的过程。 因此,构建自己的插件的能力并不像您想象的那样困难。

PostCSS can be used to polyfill real W3C features. There are a lot of plugins that aim to implement features from new W3C specifications. This will enable you to write code that respects standards and is likely to be compatible with future versions of CSS.

PostCSS可用于填充真实的W3C功能。 有许多插件旨在实现新的W3C规范中的功能。 这将使您能够编写符合标准并且可能与CSS的未来版本兼容的代码。

使用PostCSS (Using PostCSS)

Theory is great, but let’s move on to some juicy practice. Let’s install PostCSS and see what it can actually do. We won’t go into much detail about setting up proper project builds, since that’s a topic that deserves an article of its own. Instead we’ll run PostCSS directly from the command line. You can find more info on using PostCSS with your favourite build tool on its Github page.

理论很棒,但让我们继续进行一些多汁的实践。 让我们安装PostCSS并查看其实际功能。 我们不会详细介绍如何设置适当的项目构建,因为这是一个主题,值得一读。 相反,我们将直接从命令行运行PostCSS。 您可以在其Github页面上找到有关将PostCSS与您最喜欢的构建工具一起使用的更多信息。

安装PostCSS (Installing PostCSS)

PostCSS is installed via node and npm, so make sure you have those installed before you start. To install PostCSS globally on your system run:

PostCSS是通过node和npm安装的,因此在开始之前请确保已安装了这些CSS。 要在系统上全局安装PostCSS,请运行:

npm install -g postcss-cli

You can make sure it’s working by running:

您可以通过运行以下命令确保其正常工作:

postcss --help

This will give you a list of parameters that the CLI accepts. You can also find these in the postcss-cli documenation.

这将为您提供CLI接受的参数列表。 您也可以在postcss-cli文档中找到这些内容 。

运行PostCSS (Running PostCSS)

Now that we have PostCSS installed, let’s give it something to work with. Create a styles.css file in your project folder and add some CSS. For example, define a flexbox container:

现在我们已经安装了PostCSS,让我们给它一些有用的东西。 在您的项目文件夹styles.css创建一个styles.css文件,并添加一些CSS。 例如,定义一个flexbox容器:

.container { display: flex; }

Flexbox is a great feature, but it does require vendor prefixes to run on certain browsers. I would hate to maintain these manually. Fortunately, Autoprefixer, one of the most popular PostCSS plugins does exactly that. It automatically adds vendor prefixes based on the information provided via Can I use. I’ll show you how to use it to keep our vendor prefixes up to date.

Flexbox是一个很棒的功能,但是它确实需要供应商前缀才能在某些浏览器上运行。 我不愿手动维护这些。 幸运的是, Autoprefixer (最受欢迎的PostCSS插件之一)可以做到这一点。 它会根据“ 我可以使用”提供的信息自动添加供应商前缀。 我将向您展示如何使用它来使我们的供应商前缀保持最新。

To install Autoprefixer run:

要安装Autoprefixer,请运行:

npm install -g autoprefixer

Next, navigate to your project folder and create a dist folder that will contain the processed CSS:

接下来,导航到您的项目文件夹并创建一个dist文件夹,其中将包含已处理CSS:

mkdir dist

Then run PostCSS:

然后运行PostCSS:

postcss -u autoprefixer styles.css -d dist

What this says is: run Autoprefixer on styles.css and save the output to dist/styles.css. Now if you open dist/styles.css you will see your CSS with all of the required vendor prefixes:

这是说: 在styles.css上运行Autoprefixer并将输出保存到dist/styles.css 。 现在,如果您打开dist/styles.css您将看到带有所有必需的供应商前缀CSS:

.container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; }

If you run PostCSS with a -w flag, this will also start a watcher process and automatically rebuild styles.css each time the file is modified.

如果使用-w标志运行PostCSS,则每次修改文件时,这还将启动观察程序并自动重建styles.css 。

插件配置 (Plugin Configuration)

We can configure Autoprefixer to add prefixes according to the browsers we plan on supporting. This can be done using the browsers option. When running PostCSS via the CLI, plugin configuration needs to be defined in a separate .json file, for example, postcss.json. Let’s create the file in the current folder and configure Autoprefixer to support the 2 most recent versions of each browser.

我们可以配置Autoprefixer来根据我们计划支持的浏览器添加前缀。 可以使用browsers选项来完成。 通过CLI运行PostCSS时,插件配置需要在单独的postcss.json文件中定义,例如postcss.json 。 让我们在当前文件夹中创建文件,并将Autoprefixer配置为支持每个浏览器的2个最新版本。

{ "autoprefixer": { "browsers": ["last 2 versions"] } }

We can now re-run the PostCSS watcher with the new configuration file:

现在,我们可以使用新的配置文件重新运行PostCSS watcher:

postcss styles.css -u autoprefixer -c postcss.json -d dist -w

启用源地图 (Enabling Source Maps)

Source maps are essential for debugging compiled CSS. PostCSS can generate inline source maps in the output file if you add the --map option (or the -m flag).

源映射对于调试已编译CSS是必不可少的。 如果添加--map选项(或-m标志),则PostCSS可以在输出文件中生成内联源地图。

甚至更多的插件 (Even More Plugins)

PostCSS has an amazing number of plugins for linting, quality checks, fallback, old browser support, inlining assets, generating sprites, optimisation, new syntax support, and future CSS features. As mentioned, you can find a structured catalogue of plugins at postcss.parts.

PostCSS拥有大量插件,可用于棉绒,质量检查,后备,旧版浏览器支持,内联资产,生成Sprite,优化,新语法支持以及将来CSS功能。 如前所述,您可以在postcss.parts找到结构化的插件目录。

To give you a sample, here are a few more plugins that demonstrate the power of PostCSS.

为了给您一个示例,这里有更多的插件演示了PostCSS的功能。

CSS变量的自定义属性插件 (The Custom Properties Plugin for CSS Variables)

The postcss-custom-properties plugin aims to implement support for the W3C custom properties specification (aka native variables). It allows you to define custom properties in a selector with arbitrary values and reference these in other places in the stylesheet.

postcss-custom-properties插件旨在实现对W3C自定义属性规范 (即本地变量 )的支持。 它允许您在选择器中定义具有任意值的自定义属性,并在样式表的其他位置引用这些属性。

This serves a similar purpose to Less and Sass variables: to store common values and eliminate code duplication. The main difference is that the scoping mechanism is a bit different; similar to regular properties, CSS custom properties propagate along the element cascade, instead of being block scoped.

这与Less和Sass变量具有相似的用途:存储公用值并消除代码重复。 主要区别在于作用域机制有所不同。 与常规属性类似,CSS自定义属性沿元素级联传播,而不是在块范围内传播。

Here’s an example of how this plugin works. The following code:

这是此插件如何工作的示例。 如下代码:

:root { --container-width: 800px; } .container { width: var(--container-width); }

Will compile to:

将编译为:

.container { width: 800px; }

自定义选择器插件 (The Custom Selectors Plugin)

The postcss-custom-selectors plugin implements the Custom Selector specification. This allows you to pre-define selectors and reference them later in the code. For example, we can save all headers in one selector and re-use this as a variable:

postcss-custom-selectors插件实现了Custom Selector规范 。 这使您可以预定义选择器,并在以后的代码中引用它们。 例如,我们可以将所有标头保存在一个选择器中,然后将其重新用作变量:

@custom-selector :--headings h1, h2, h3, h4, h5, h6; :--headings { color: mediumblue; }

Which will compile as follows:

编译如下:

h1, h2, h3, h4, h5, h6 { color: mediumblue; }

俄罗斯样式表插件 (The Russian Stylesheets Plugin)

Ever wanted to learn Russian but were too busy writing CSS? No worries, you can now do both by writing CSS in Russian! Just use the Russian Stylesheets plugin. Check this out:

是否曾经想学习俄语,却又忙于编写CSS? 不用担心,您现在可以通过用俄语编写CSS来完成这两项工作! 只需使用俄语样式表插件即可。 看一下这个:

h1 { размер-шрифта: 20пикселей; цвет: красный; цвет-фона: белый; вес-шрифта: жирный; }

Which is translated into:

转换为:

h1 { font-size: 20px; color: red; background-color: white; font-weight: bold; }

Well… I never said all the plugins were equally useful!

好吧……我从未说过所有插件都同样有用!

包装东西 (Wrapping Things Up)

Preprocessors like Less and Sass are great. They have contributed much to our development process and are definitely not something we can easily leave behind. But, I feel that that the time has come to stop and reconsider whether those tools are the right way to do things in the long run.

Less和Sass之类的预处理器很棒。 它们为我们的开发过程做出了很大贡献,而且绝对不是我们可以轻易抛弃的东西。 但是,我觉得现在该停止了,重新考虑这些工具从长远来看是否是正确的做事方式。

We don’t just need new features writing stylesheets, we also need modularity, additional exposure of the new standards, as well as flexible build processes. PostCSS provides just that and might be a game changer in the CSS world.

我们不仅需要编写样式表的新功能,还需要模块化,对新标准的更多了解以及灵活的构建过程。 PostCSS正是提供了这一点,并且可能会改变CSS世界。

翻译自: https://www.sitepoint.com/an-introduction-to-postcss/

postcss

最新回复(0)