Craft By Zen

Curation  /  The Stream  /  TIL importmap

TIL importmap

Published

I forked a small demo from Wes Bos and ran in on my own sandbox. It seems much cleaner than using a script tag per each dependency, and works on all major browsers.

In my little demo app, I placed the importmap in the head of the document. I’m using react as well as my own utils file to test out the functionality.

<script type="importmap">
  {
    "imports": {
      "react-dom": "https://esm.sh/react-dom",
      "react": "https://esm.sh/react",
      "utils": "./utils.js"
    }
  }
</script>

Read more about importmap on MDN

From there, I imported these libraries in a script module.

<body>
  <div id="app"></div>
  <script type="module">
    /* eslint-disable */
    import { useState } from "react";
    import { createRoot } from "react-dom";
    import { formatMoney } from "utils";
    createRoot(document.querySelector(`#app`)).render(formatMoney(100.2365));
  </script>
</body>

I had a hiccup with [plugin:vite

] as I found countless others have, so I wrote a custom bun server to host this project. Hopefully there’s a better setup I can find with Vite using importmap in the future.