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 0% over the HTML documents you would use a script in. But in , 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:

adding type="module" to scripts in pens - add module - Adding type=&#8221;module&#8221; to Scripts in Pens

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 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.

Source link


Please enter your comment!
Please enter your name here