Native modules have arrived in JavaScript. You can write JavaScript that exports functions that can be imported and used in other scripts. MDN has a good overview of how it works and all the different syntax involved.

Here's a simple example. This is a handy-dandy little helper function:

export function getNodes(str) { 
  return new DOMParser().parseFromString(str, 'text/html').body.childNodes;

Notice I'm using export as I define the function, so it can be imported from something else. I could drop that JavaScript into a new Pen, and access that JavaScript directly. Like this:

Now if I wanted to use that function in another Pen, I could do this:

import { getNodes } from '';

let videoHTML = getNodes(`
  <div class="widget">
    <h2>I'm a widget!</h2>
    <p>I do widgeting.</p>


But there is one little thing you need to know. For that import statement to work, it needs to be inside a <script> that has <script type="module">.

That works perfectly fine in Projects, because you have 100% control over the HTML documents you would use a script in. But in Pens, your JavaScript is inserted into this template to create the preview, which you can't really control.

Now in Pens, we allow you to add it in the Pen's JavaScript settings:

See the Pen RxayBX by Chris Coyier (@chriscoyier) on CodePen.

This even opens up usage of modules from CDN's like unpkg! If an npm package is ready for it, unpkg has an experimental feature to import. Check out this usage of Three.js:

See the Pen Native Module usage from UKPKG by Chris Coyier (@chriscoyier) on CodePen.