Table of Contents
This very simple plugin walks through media AtRules and attaches the property preludeCssTreeAst
. This property is an instance of AtrulePrelude and can be traversed via the apis made available by csstree.
npm install postcss-create-mq-ast
Just the same as any other postcss plugin
const createMqAst = require('postcss-create-mq-ast')
postcss([createMqAst()])
.process(...)
I needed an ast in order to create postcss-remove-duplicate-mq
Postcss doesn't parse media queries and instead leaves them as a params property on the media AtRule
There exists the postcss-media-query-parser but that doesn't use the exposed ast structures provided by postcss (possibly because they didn't exist when it was written). It also is outdated and not maintained.
I chose to use csstree's ast because postcss has plans to utilize csstree's parser down the road.
Given the following css
/* test.css */
@media (min-width: 500px) {
body {
background-color: blue;
}
}
Here's a snippet of the resulting AtRule node
Keep in mind the csstree AST isn't pure json. They override toJSON
to provide that structure when printed
For an example of traversing this property, see postcss-remove-duplicate-mq. The apis I found most useful are csstree's walk and its (linked) List