Optimizing CSS for Google AMP
I have mixed feelings about AMP but supporting it seems like the only way to get any traction in Google searches for my fonts so here we are.
When I was updating my site less frequently, manually copying and pasting the stylesheets and cleaning them up for AMP seemed perfectly reasonable. Lately though, I’ve been trying out new designs more often and it’s been too easy to accidentally forget and let the pages get out of sync. So I decided to try creating a PostCSS plugin to automate the process.
Thinking about the changes I was making by hand, I knew I wanted my plugin to filter out:
- Media queries for desktop breakpoints
- Non -webkit- vendor prefixes
- Specific block names or other prefixes (for BEM or other namespacing)
- !important flags
- -amp classes or i-amp tags
The PostCSS guidelines are pretty clear that a plugin should “do one thing, and do it well” and provide some examples using monorepos to handle more complex tasks. I’ve been meaning to work more with Lerna so this seemed like a good excuse.
The result is the postcss-amplify plugin. You can check out Github for instructions on how to use it with your current PostCSS setup or I made a web interface for quick use. If you try it and notice anything weird, let me know in the comments or by submitting an issue. I think my next step will be to create a Webpack plugin to fully automate my build so keep an eye out for that.