I will cut the long story short and go directly to the point: there is an npm package that simplifies greatly the task of converting snippets to live pens on codepen. Here is the howto:

Before we go on, I need to point out that there is one hard requirement and that is to allow html in the markdown files.
Eleventy defaults to html: false which is also the default for the markdown-it Library.

  • Make sure you have enabled it in your configuration!
  • Eg:
/* Markdown Overrides */
let markdownLibrary = markdownIt({
  html: true,
  breaks: true,
  linkify: true,
});
eleventyConfig.setLibrary("md", markdownLibrary);

Installation

Installation should follow the usual NPM dance:

npm i -D 11ty-to-codepen

Usage

First, configure your .eleventy.js:

  • Import it and define the shortcode:
// At the top of the file add:
const codepenIt = require("11ty-to-codepen");

// Somewhere before the final return add:
eleventyConfig.addPairedShortcode("codepen", codepenIt);
  • Use it in any .md file. Check the README file for the full explanation of the possible attributes.

Here's a Live example:

Some very important HTML code:

<h1 class="someClass" style="--grad:0deg; --grad-color:#3188c1;">Test</h1>

Some very important CSS code:

body {
  margin: 4rem;
}

Some very important JavaScript code:

import { render, html, svg } from "https://unpkg.com/uhtml?module";

const h1 = document.querySelector("h1");

h1.style.setProperty("--grad-color", "rebeccapurple");

render(document.body, html`${h1}`);

Click the following button to open the above 3 snippets on Codepen: