css 處理插件大致分為壓縮css和給css添加瀏覽器兼容前綴。
cssmin 可以壓縮css,大致原理是將使用正則將css 中的注釋和空格刪除。
px2rem 插件是將css 中的px 轉換為 rem,它的原理是 調用了css 的AST對象 ,css插件將css內容解析成 一個javascript對象,即css AST 抽象語法樹,然后遍歷語法樹,將對象中的px轉換為rem,然后再將對象轉換為css文件。
這是一些獨立的css處理插件,目前css 處理插件最火的就是postcss
postcss 只是一個平台,它只負責將css 轉換成AST語法樹,然后,運行postcss上的插件修改css Ast對象,最后將AST轉換為css內容。
我們自己也可以編寫postcss 插件,按照官方的例子:https://dockyard.com/blog/2018/02/01/writing-your-first-postcss-plugin 很快就可以實現一個簡單的post css 插件
post 轉換為css語法的原理是:將每一個selector 歸為一塊 名為rule,然后將selector 內的每一個屬性歸為一塊,名為declaration
插件可以遍歷這些屬性,然后更改例子:
如果
var postcss = require('postcss')
module.exports = postcss.plugin('postcss-test-plugin', function (opts) {
opts = opts || {}
// Work with options here
return function (root, result) {
//遍歷 所有的 rule
root.walkRules(function(rule){
//打印出rule 的選擇器
console.log(rule.selector)
// 遍歷rule內所有的 declaration,
rule.walkDecls(function(decl){
// 打印出 屬性 和值
console.log(decl.prop+" = "+decl.value)
})
})
}
})
以一個簡單的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
