Skip to content

postcss 也是利用了 AST,它将 CSS 中的节点分类如下:

  1. Root 代表节点树的顶级对象,实际上就是每一个 CSS 文件。
  2. AtRule 代表以 @ 开头的语句,譬如 @charset "UTF-8"@media (screen) {}
  3. Rule 代表的是 CSS 选择器,譬如 input, button {}
  4. Declaration 代表的是 CSS 键值对语句,譬如 color: black
  5. Comment 代表的是块级注释

上述的每个节点都有 enterexit事件监听

按照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')({})
    ]
  }
}