|

my personal blog

What If Your JS Package CDN URL Goes Missing?

January 7, 2024

Recently a package my webapp imported suddenly disappeared. The index.html imported the package via CDN e.g. <script src=https://unpkg.com/...package.umd.min.js>, which returns 404 Not Found.

How do we resolve this?

One option is to setup a build tool like Vite, Webpack etc. and npm install the JS package that we need. This might be more effort than it’s worth for a minimal webapp. Another way I came across recently is through the combination of Import Maps and JSPM.

Why isn’t using Import Maps sufficient? Can’t we just write something like this,

//index.html
<script type="importmap">
  {
    "imports": {
      "browser-fs-access": "https://unpkg.com/[email protected]/dist/index.modern.js"
    }
  }
</script>

//app.js
import {fileOpen} from 'browser-fs-access';

In the case above, yes, since the dependencies are all compatible with the browser. However, sometimes we’ll run into a dependency that expects a node runtime e.g. the library executes process.env.node_env, which errors since the browser doesn’t have a process object.

That’s where JSPM comes in. JSPM can generate an Import Map that will contain the appropriate imports as well as scopes to ensure dependencies have browser compatible shims/pollyfills.