TL;DR: How do I “require” modules on a CDN or hosting service?
Details:
My repos are “hosted” on github via the github pages technique.
How do I “require” (import) these? I have two formats for all repos (es6 modules and IIFE’s for script tag use). Also some with a third commonJS format.
I tried using es6 import statements, which I’d prefer, but that failed. Should that work?
Then tried require() of both the IIFE and cjs formats, also w/o luck.
I then found this stunt for loading the IIFEs:
ascore = require(‘https://backspaces.github.io/as-core/dist/AS.js’)
.catch(() => window.AS)
This did work, but seems odd.
So how do I import/require from a web server?
ES imports work, as long as you import
a valid ES module. For example:
d3 = import("https://unpkg.com/d3-color@1.0.3/index.js?module")
Or, taking advantage of Observable’s built-in support for loading ES modules from unpkg:
d3 = import("d3-color@1")
So this works:
AS = import("https://backspaces.github.io/as-core/dist/AS.module.js")
For require
, you need an AMD bundle (or more commonly, a UMD bundle) for it to work out of the box. If you have an IIFE or a CJS bundle, you’ll need to adapt it. The pattern of catching the error and pulling out the global AS
as you discovered is the standard pattern for loading an IIFE. But, it’s better for library authors to publish UMD bundles or ES modules for broader compatibility. Tom’s written a post on requiring “stubborn” modules.
2 Likes