Using ESM Syntax to import JS Packages from a CDN (Skypack)

Miffy Chen
2 min readJul 15, 2020

--

ESM stands for ECMAScript Modules. A module is a JavaScript file that allows imports and exports of one or more values (objects, functions, variables, etc) using the import / export keyword.

You often see this syntax when a module is imported in JavaScript:

import React from 'react';
import { foo, bar } from './myFolder';
const package = require('module-name');

Starting with ECMAScript 6 and HTML5, we were given the option to add modules to an HTML page by using a <script> tag with the special type="module" attribute:

<script type="module" src="index.js"></script>

While ESM works with most modern browsers, you should always add a type="nomodule" when using type="module" :

<script type="module" src="module.js"></script>
<script nomodule src="fallback.js"></script>

It is also important to note that any script loaded with type="module" is loaded in strict mode, and your CORS header must allow cross-site loading (ex: Access-Control-Allow-Origin: *).

Now that we are done introducing the basics for ESM Syntax, let’s move on to JavaScript CDNs!

Most modern web apps use some type of JS library or framework, installed via npm (Node Package Manager), and bundled using module bundlers such as Webpack or Rollup.

While bundlers are still pretty mainstream, there are significant performance benefits to using a CDN:

On July 13, 2020, Pika introduced a brand new JavaScript CDN at the ESNext Conf 2020 named Skypack.

It’s a new CDN service that claims to be an upgrade of older CDNs such as UNPKG, offering faster loading speeds and an even friendlier approach.

If you have used unpkg before, you would know that by attaching the name of any package you can find on npm to unpkg’s address, you will gain access to the root js file as designated in its package.json. For example: https://unpkg.com/react

Skypack works exactly the same! So why bring it up you ask?

Because when we combine Skypack with the HTML <script type="module"> tag, we get something very cool! The ability to import libraries and frameworks as modules in a plain HTML document!

No more typing npx create-react-app my-app to spin up a whole React project. Enjoy!

--

--