I love playing with PostCSS plugins in CodePen. Checkout these pens using Write SVG and Short.

CodePen comes bundled with a nice set of PostCSS plugins, but we can easily add our own using CodePen’s External Resources.

We can embed a PostCSS plugin in 3 steps.

  1. We create a browserified version of a PostCSS plugin.
  2. We save that browserified plugin to a Pen on CodePen.
  3. We embed that Pen anywhere we want!

These steps go from hard and to easy, so let’s get started.


Creating a browser-safe version of a PostCSS plugin

Here’s the hard part — we’re going to manually turn a PostCSS plugin into a CodePen plugin.

First, we clone our favorite PostCSS plugin:

  git clone https://github.com/jonathantneal/postcss-short.git

Next, from the plugin directory, we install these dependencies:

  npm install --save-dev browserify babel-cli babel-preset-env uglify-js && npm install

  1. Now, from the plugin directory, we create a file called codepen.js and give it these contents:
  // load a PostCSS plugin
const plugin = require('.');

// update <style> after running its contents through a PostCSS plugin
const updateStyle = (style) => {
    plugin.process(style.textContent, { /* plugin options go here */ }).then(
        (result) => {
            style.textContent = result.css;
        },
        console.error
    );
};

// update any pre-existing <style> in <head> using the PostCSS plugin
const styles = document.head.getElementsByTagName('style');

if (styles.length) {
    Array.prototype.forEach.call(styles, updateStyle);
}

// watch for and update any new <style> in <head> using the PostCSS plugin
(new MutationObserver(
    (mutations) => mutations.forEach(
        (mutation) => Array.prototype.filter.call(
            mutation.addedNodes || [],
            (node) => node.nodeName === 'STYLE'
        ).forEach(updateStyle)
    )
)).observe(
    document.head,
    {
        childList: true
    }
);

Finally, we compile that codepen.js to codepen.bundle.js:

  browserify codepen.js | babel --presets=env | uglifyjs --compress --mangle > codepen.bundle.js

The hard part is over. I promise.


Saving a browserified PostCSS plugin to a Pen

Let’s copy and paste the contents of our codepen.bundle.js into the JS tab of a new Pen. We can test our plugin out by writing some CSS that leverages the plugin. If everything is working, let’s save the Pen!

I like to save mine with a name like postcss-write-svg@3.0.2.


Embedding a Pen anywhere

Lastly, we can add .js to the URL of our Pen to see its raw JS. We can embed this URL as an External Resource in any other Pen.


That’s it. We can embed that JS into any other Pen to automatically use our PostCSS plugin (or plugins). Happy PostCSS’ing!

@jon_neal


2,139 3 16