Importing modules from the internet

Time Box

ActivityTime
Reading0.5 hours
Exercise1 hour

One of the most exciting aspects of modules is that they make it easy to use code that you didn't have to write.

Since many publicly available Javascript libraries were published long before ESM was available, you have to make sure the library you want to use is formatted correctly for use directly in the browser.

There are some Content Delivery Networks (CDNs) that specialise in delivering ESM, like Skypack and esm.sh.

For example, there is a package on npm called "canvas-confetti", if we want to use it directly in the browser we can get it from Skypack.

import confetti from 'https://cdn.skypack.dev/canvas-confetti'
confetti()

Exercise

Create a folder at exercises/import-from-web with index.html and main.js files, and use skypack to import an npm package and demo some functionality. One option is the animation library motion.

In their documentation, they will give you an import that looks like this:

// NOPE! This is not for us
import { animate } from 'motion'

This has an assumption that you're using a bundler, package manager, import-map or some other fancy tooling.

We're going to use native JavaScript Modules and skypack to import the library.

// YES! This is more our style
import { animate } from 'https://cdn.skypack.dev/motion'

Remember to run npx serve in the root folder of your project and open the url it logs to your terminal (usually http://localhost:3000/).

If you an HTML file directly from your browser, it uses the file:// protocol and a lot of web features including JavaScript Modules do not work with the file:// protocol. So always develop with a web server.