Recursive ES module loader

Loading external modules on Observable is like compiling and installing software packages without package managers. You hit enter and bless until it errs and ends up with mysterious messages 90% of the time.

Thanks to ES modules, there is finally a reliable and standardized way to import a module for JS, even in browsers, and we can see more and more packages starting offering ES modules in their repositories or CDNs. However, ES modules in browsers are interpreted in terms of URLs, unlike in Node.js where module names are searched in folders. Without bundling, most ES modules still will not run on browsers.

Maybe the most exciting fact on ES modules is that imports / exports are static. One can statically analyze a file and peel out its dependencies without side-effects. This fact motivates me to write a ES module resolver: Fetching the source code (if CORS is allowed), patching it, and turning it to a blob URL. Then the browser can take over and set everything up.

Here is my module: https://observablehq.com/@andy0130tw/esm-loader. I use it to power up CodeMirror 6 but there must be much room for improvement, so suggestions are welcome.

4 Likes