Modern frontend apps with ES modules and import maps

Published on

With import maps you can map external module names to their relative URLs, on a CDN for example, which makes it super easy to use external modules, natively in 2023.

By defining a <script type="importmap"> tag you can map the various modules you like to include in your web application, leveraging ES modules.

Put the mapping the in the <head> tag of the document and can import modules using the import tag inside a <script type=“module”> tag.

Additionally, if you want to gracefully degrade the application somehow, or progressively enhance if you prefer, you can use HTMLScriptElement.supports('importmap') to detect if the browser supports import maps.

Example

Define a <script type=“importmap”> in the <head> section with the following content:

{
  "imports": {
    "app": "/modules/app.js",}
}

Now inside a <script type=“module”> tag you can import the app module, e.g.:

import {mount, render,} from “app”

For more info check out web.dev with their great article on the subject.

PS: I use unpkg as a CDN in my hobby projects and I’m super happy with it

Here, have a slice of pizza 🍕