I’ve been having a bit of fun testing PostCSS plugins in CodePen, like PostCSS Write SVG and PostCSS Short.

CodePen already comes bundled with a nice list of PostCSS plugins, but you can easily test your own by using Templates and External Resources.

First, write something that updates the contents of a <style> element after running it through a PostCSS plugin.

  const plugin = require('postcss-write-svg');

const updateStyle = (style) => {
        (result) => {
            style.textContent = result.css;

Next, use that function to update any <style> elements in <head>. This catches any CSS already saved to a Pen.

  const styles = document.head.getElementsByTagName('style');

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

Use MutationObserver to watch for new <style> elements. This catches any changes to the Pen, which is useful during live-coding.

  (new MutationObserver(
    (mutations) => mutations.forEach(
        (mutation) => Array.prototype.filter.call(
            mutation.addedNodes || [],
            (node) => node.nodeName === 'STYLE'
        childList: true

Now, use browserify to bundle this script and the PostCSS plugin together into one file.

I also use babel and Uglify to maximize browser compatibility and compress the script as much as possible. Most bundles end up being about 30kb, about the size of a small image.

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

Actually, I wrapped the whole thing into a package.json:

  "name": "postcss-write-svg-codepen",
  "scripts": {
    "test": "browserify codepen.js | babel --presets=es2015 | uglifyjs --compress --mangle > codepen.bundle.js",
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-preset-es2015": "^6.18.0",
    "browserify": "^13.1.1",
    "postcss-write-svg": "^3.0.1",
    "uglify-js": "^2.7.5"

The hard part is over. Now move the bundle into CodePen.

Copy and paste the bundled JavaScript into the JS tab of a new Pen. Test it out by writing some CSS that uses the plugin. If everything is working, save the Pen. I like to save it with a name like postcss-write-svg@3.0.2 and mark it as Private.

Add .js to the URL of this Pen to see a raw copy of the bundle. This URL can be included as an External Resource in any other Pen that wants to use this PostCSS plugin.

I recommend making your bundle sharable by creating a new Template. To do this, create a new Pen, open its Settings, and mark it as a Template. Then, goto the JavaScript tab and in the Add External JavaScript section paste the .js URL you just created.

That’s it. Now you can use this Template to make new Pens that automatically include your PostCSS plugin (or plugins). Happy PostCSS’ing!


989 3 12