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 automatically convert px to rem in postcss plug-in

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

Share

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

This article will explain in detail how to automatically convert px to rem in the postcss plug-in, the content of the article is of high quality, so the editor shares it for you to do a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Postcss is the transpiler of css, which can analyze and transform css code just as babel does to js as babel does to js. At the same time, it also provides plug-in mechanisms to do custom transformations.

The principle of postcss

Postcss is the translator from css to css. Like babel, it is divided into three stages: parse, transform and generate. Various transformation plug-ins are working in the transform phase, based on AST to do analysis and transformation.

Css's AST is much simpler than js's, and there are several main ones:

Atrule: rules that start with @, such as:

@ media screen and (min-width: 480px) {body {background-color: lightgreen;}}

Rule: the rule at the beginning of the selector, such as:

Ul li {padding: 5px;}

Decl: specific styles, such as:

Padding: 5px

Is it much simpler than the dozens of AST of js parser?

These can be viewed visually through astexplorer.net.

How to write the postcss plug-in

The postcss plug-in works in the transform phase and deals with ast nodes. The plug-in takes the following form:

Const plugin = (options = {}) = > {return {postcssPlugin: 'plug-in name', Rule (node) {}, Declaration (node) {}, AtRule (node) {}}

The outer function accepts options, returns an object of a plug-in, declares the listener of what node to handle, and then writes the processing logic in the corresponding listener.

You can also write:

Module.exports = (opts = {}) = > {return {postcssPlugin: 'plug-in name', prepare (result) {/ / here you can put some common logic return {Declaration (node) {}, Rule (node) {}, AtRule (node) {}

Return various listener in prepare, which has the advantage of storing some common logic compared to the first.

You can then run the plug-in like this:

Const postcss = require ('postcss'); postcss ([plugin ({/ / options})]). Process (' a {font-size: 20px;}'). Then (result = > {console.log (result.css);})

Let's write a simple plug-in from px to rem to practice.

Requirement description of actual combat case

Px is a fixed unit of length, and the size of the device viewport is various, we want to use a set of styles to adapt to the display of various devices, we need relative units, commonly used is rem.

The essence of rem is proportional scaling, relative to the font-size of the html element.

For example, if the font-size of html is set to 100px, then 1rem equals 100px, and the subsequent style is written as 2rem if it is 200px.

In this way, we only need to modify the font-size of html to adapt to the display of various screen widths, and the specific units will be scaled proportionally.

We have to convert all px to rem according to the font-size value of html, which is usually done manually, but it is more tedious. After knowing the calculation method, we can use the postcss plug-in to do it automatically.

Next, let's implement this postcss plug-in

Code implementation

Let's take a look at the basic structure of the plug-in, just declare the listener that handles Declaration:

Const plugin = (options) = > {return {postcssPlugin: 'postcss-simple-px2rem', Declaration (decl) {}

Then all you need to do is convert the px in the style value of decl to rem, and simply replace it with regular substitution:

Const plugin = (options) = > {const pxReg = / (\ d +) px/ig; return {postcssPlugin: 'postcss-simple-px2rem', Declaration (decl) {decl.value = decl.value.replace (pxReg, (matchStr, num) = > {return num/options.base +' rem';});}}

Replace through the replace method of the string, the first parameter is the matching string, the subsequent parameter is the grouping, and the first grouping is the value of px.

Calculating the rem corresponding to px requires the corresponding px value for 1rem, which can be passed through options.

Then let's test it:

Postcss ([plugin ({base: 100})] .process ('a {font-size: 20px;}') .then (result = > {console.log (result.css);})

As you can see, the conversion has been done correctly:

Of course, our plug-in is just a case study, not perfect enough, and more complex rules are needed to improve it.

Summary

Postcss is the transpiler of css, just as babel is the transpiler of js, and the AST of postcss has only a few nodes, which is relatively simple, and can also be viewed visually through astexplorer.net.

Postcss also provides plug-in functionality that allows you to do some custom analysis and transformation.

We have implemented a simple plug-in that automatically converts px to rem:

Rem is through proportional scaling to achieve a set of style to adapt to different device width display scheme, need to do px to rem conversion, this can be done automatically with the postcss plug-in.

In fact, the postcss plug-in analysis and conversion functions there are many applications, such as switching theme colors, from white to black, you can use postcss to automatically analyze the value of the color, and then do conversion.

On the postcss plug-in how to automatically convert px to rem to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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