关于css 的AST 语法树的理解
css 處理插件大致分為壓縮css和給css添加瀏覽器兼容前綴。
cssmin 可以壓縮css,大致原理是將使用正則將css 中的注釋和空格刪除。
px2rem 插件是將css 中的px 轉(zhuǎn)換為 rem,它的原理是 調(diào)用了css 的AST對(duì)象 ,css插件將css內(nèi)容解析成 一個(gè)javascript對(duì)象,即css AST 抽象語(yǔ)法樹(shù),然后遍歷語(yǔ)法樹(shù),將對(duì)象中的px轉(zhuǎn)換為rem,然后再將對(duì)象轉(zhuǎn)換為css文件。
?
這是一些獨(dú)立的css處理插件,目前css 處理插件最火的就是postcss
postcss 只是一個(gè)平臺(tái),它只負(fù)責(zé)將css 轉(zhuǎn)換成AST語(yǔ)法樹(shù),然后,運(yùn)行postcss上的插件修改css Ast對(duì)象,最后將AST轉(zhuǎn)換為css內(nèi)容。
我們自己也可以編寫(xiě)postcss 插件,按照官方的例子:https://dockyard.com/blog/2018/02/01/writing-your-first-postcss-plugin?很快就可以實(shí)現(xiàn)一個(gè)簡(jiǎn)單的post css 插件
post 轉(zhuǎn)換為css語(yǔ)法的原理是:將每一個(gè)selector 歸為一塊 名為rule,然后將selector 內(nèi)的每一個(gè)屬性歸為一塊,名為declaration
插件可以遍歷這些屬性,然后更改例子:
如果
var postcss = require('postcss')module.exports = postcss.plugin('postcss-test-plugin', function (opts) {opts = opts || {}// Work with options herereturn function (root, result) {//遍歷 所有的 ruleroot.walkRules(function(rule){//打印出rule 的選擇器console.log(rule.selector)// 遍歷rule內(nèi)所有的 declaration,rule.walkDecls(function(decl){// 打印出 屬性 和值 console.log(decl.prop+" = "+decl.value)})})} })以一個(gè)簡(jiǎn)單的css為例
:
.item-right {
text-align: right
}
.item-left {
line-height: 24px
}
輸出是:
.item-right
text-align = right
.item-left
line-height = 24px
例子地址 https://github.com/muyiwei/postcss-plugin-test.git
?
轉(zhuǎn)載于:https://www.cnblogs.com/chillaxyw/p/10705929.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的关于css 的AST 语法树的理解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: sock 文件方式控制宿主机_sock
- 下一篇: 东北天到ecef的变换_GNSS学习笔记