brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: an HTML import map lets your scripts import a library by a short name

Html
~/tips/tip-html-importmap-bare-names

import { format } from "dates";

Write import statements without long URLs and without a build step.

For a small project I do not always want a bundler just so I can write a short import. An import map teaches the browser what a name means.

Declare the map in the page, then use the name in a module:

<script type="importmap">
{
  "imports": {
    "dates": "/js/vendor/dates-2.1.js",
    "lib/": "/js/lib/"
  }
}
</script>
<script type="module">
  import { format } from "dates";
  import { chart } from "lib/chart.js";
</script>

The browser swaps dates for the real path. A key ending in a slash maps a whole folder. When a new version arrives, I change one line in the map and every file that imports dates follows.

Order matters: the map has to come before any module script that relies on it, so I put it high in the head. The JSON must be valid, which means double quotes and no trailing comma. It only affects import statements and import(), so the src of a script tag is not rewritten. It also does not download or bundle anything for you, the files still need to exist where the map says.

Further reading: MDN: script type importmap

More Html tips width="640" height="360" poster="demo.jpg"> The HTML optgroup element puts headings inside a long dropdown srclang="en" label="English" default> An HTML noindex meta tag keeps one page out of search results title="Example blog" href="/feed.xml"> All Html tips (14) All topics

Link