postcss 也是利用了 AST,它将 CSS 中的节点分类如下:
Root代表节点树的顶级对象,实际上就是每一个CSS文件。AtRule代表以@开头的语句,譬如@charset "UTF-8"或@media (screen) {}。Rule代表的是CSS选择器,譬如input, button {}。Declaration代表的是CSS键值对语句,譬如color: black。Comment代表的是块级注释。
上述的每个节点都有 enter 和 exit 的事件监听。
按照Writing a PostCSS Plugin文章中所著,创建一个私人的自定义 reverse 插件。
js
// reverse/index.js
/**
* @type {import('postcss').PluginCreator}
*/
module.exports = (opts = {}) => {
// Work with options here
return {
postcssPlugin: 'reverse',
Root (root, postcss) {
// Transform CSS AST here
root.walkDecls(decl => {
decl.prop = decl.prop.split('').reverse().join('')
})
}
/*
Declaration (decl, postcss) {
// The faster way to find Declaration node
}
*/
/*
Declaration: {
color: (decl, postcss) {
// The fastest way find Declaration node if you know property name
}
}
*/
}
}
module.exports.postcss = true在 .postcssrc.js 引入即可使用:
js
// .postcssrc.js
module.exports = ctx => {
return {
plugins: [
require('./plugins/reverse/index.js')({})
]
}
}