Custom PostCSS Plugins
Write your own PostCSS plugin to transform CSS nodes programmatically.
Why Write a Custom Plugin?
When no existing PostCSS plugin solves your need — a project-specific CSS transformation, migration helper, or custom lint rule — writing a custom plugin gives you direct access to the CSS AST.
Plugin Structure
A PostCSS plugin is a function that receives a Root node (the parsed CSS) and optionally a Result object. Use the postcss.plugin() factory or the modern direct function approach:
// my-plugin.js
const plugin = () => {
return {
postcssPlugin: 'my-plugin',
Declaration(decl) {
// Called for every declaration node
},
Rule(rule) {
// Called for every rule node
}
};
};
plugin.postcss = true;
module.exports = plugin;All lessons in this course
- What PostCSS Does and How It Works
- Autoprefixer and cssnano
- Custom PostCSS Plugins
- PostCSS in Vite and Webpack