Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand postCSS

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to understand postCSS". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand postCSS.

TailwindCSS, which has been very popular recently, has a feature:

You can remove css selectors that are not used by the project from the compiled css file.

This function is implemented by PurgeCSS.

Linking TailwindCSS to PurgeCSS is a postCSS plug-in @ fullhuman/postcss-purgecss.

Not only TailwindCSS, but also many well-known projects use the postCSS plug-in. For example:

Many people use the autoprefixer plug-in in their projects to add different "browser prefixes" to css selectors.

Internally, the browser version is specified according to browserslist [1].

Then go to caniuse [2] to find out the compatibility support of the browser version.

Finally, the unsupported css attributes are overwritten through the ability of postCSS.

As you can see, postCSS is increasingly becoming an essential dependency for front-end projects.

At the same time, there are many misunderstandings about postCSS, such as thinking that he is the same "css preprocessor" as Less and Sass.

This article will introduce postCSS from the bottom up. I hope this article will give you a deeper understanding of this mass killer.

What is postCSS?

PostCSS is a css compiler.

The analogy @ babel/parser of the Babel family can parse the js code into AST (abstract syntax tree), then rewrite AST with the power of many plug-ins (@ babel/plugin-xx), and finally output the rewritten js code.

PostCSS can parse css code into AST using its own parser, then rewrite AST with many plug-ins (autoprefixer introduced above is one), and finally output the rewritten css code.

From this point, we can see that it is different from the "css preprocessor" such as Less-the input and output products of postCSS are css files.

As a result, postCSS is also called a "post-processor" because it is usually at the end of the css processing chain.

AST of postCSS

You can choose from astexplorer [3]:

Language: css

Parser:postCSS

Learn how postCSS parses css.

For example, for the following css code:

/ * I am KaSong * / @ media screen and (min-width: 900px) {article {padding: 1rem 3remt;}} ul {margin: 3remt;} ul li {padding: 5px;}

Will be parsed by postCSS into AST with the following tree structure:

There are several types of nodes:

Root: root node, which represents a css file

AtRule: statements that begin with @, such as @ charset "UTF-8" or @ media (screen) {}

Rule: internally contains defined selectors, such as input, button {}

Declaration:key-value key-value pairs, such as color: black

Comment: a separate comment. The parameters of selectors and at-rule and the comments of value are in the node attribute of the node.

Implement a simple plug-in

Next, let's see how developers get involved in the postCSS compilation process from the implementation of a plug-in.

Postcss-focus [4] adds: focus to all: hover selectors to improve the availability of keyboard operations.

For the following code:

.a: hover, .b: hover, .c: hover {opacity: .5;}

After being processed by the plug-in, it will output:

.a: hover, .b: hover, .c: hover, .a: focus, .b: focus, .c: focus {opacity: .5;}

After installing postcss and postcss-focus, you can see the results on the console through the following demo:

Const postcssFocus = require ('postcss-focus'); const postcss = require (' postcss'); const fs = require ('fs'); / / input css file address const from =' src/a.css'; const to = 'output/a.css'; fs.readFile (from, (err, css) = > {postcss (postcssFocus) .process (css, {from, to}) .then (result = > {console.log (result.css)})})

Next, we analyze the implementation logic of the postcss-focus source code [5]:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

PostCSS parses the input css to AST

Traverse all Rule type nodes in AST

Maintain an array that traverses all the selector of this node, each traversal to a selector containing: hover push one in the array: focus's selector

After transferring the array concat obtained in 2 to the existing selectors of this node

Output a new AST based on the changed css

The core source code is as follows:

{postcssPlugin: 'postcss-focus', / / step 1 Rule: rule = > {/ / step 2 if (rule.selector.includes (': hover')) {let focuses = [] for (let selector of rule.selectors) {if (selector.includes (': hover')) {let replaced = selector.replace (/: hover/g,': focus') if (! hasAlready (rule.parent) Replaced) {focuses.push (replaced)} / / step 3 if (focuses.length) {rule.selectors = rule.selectors.concat (focuses)}

This plug-in is only to demonstrate the basic working methods of the plug-in, in fact, the implementation of the plug-in is rather rough.

PostCSS provides detailed plug-in creation documentation [6]. The template code that create-postcss-plugin [7] uses to create plug-ins is even provided.

More possibilities

Because it provides the ability to express and rewrite css AST, the plug-in of postCSS can achieve very multi-function. For example:

Postcss-functions

The Declaration node describes the key-value pair that expresses the "css attribute", where the value is of type "string".

Then it is entirely possible to customize the resolution rules of the value.

Body {color: getColor ();}

By defining a getColor function and parsing it into a function execution in AST, you can write logical code in a css file with js.

This is postcss-functions [8]

Stylelint

Configure different lint rules to realize the static syntax detection of css. This is stylelint [9]

Summary

Currently, postCSS plug-ins can be divided into the following categories by function:

Solve global css problems, such as providing css module [10] support

Use css features that are not fully compatible, such as autoprefixer [11]

Formatting to improve css readability

Picture and word processing

Linters, such as stylelint

Css support for different syntax, such as postcss-html [12], can parse in class html files

Read here, I believe you will agree: compared to Less, Sass,postCSS is the big killer in the field of css processing.

At this point, I believe you have a deeper understanding of "how to understand postCSS". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report