Import maps in JavaScript

By Sander Borgman

3 min read

Traditionally, developers have used build tools like Webpack or Rollup to bundle and optimize their code for production. These build processes can be time-consuming to set up and make development more complicated. With native JavaScript modules now widely supported in modern web browsers, there is a need to map JavaScript packages to their source files.

Authors

Let's say we have the following JavaScript module on our page:

<script type="module">
  import moment from 'moment'
  // ...
</script>

Without a bundler, the browser will not be able to resolve the moment package.

In this blog post, we'll explore import maps to solve this problem and show you how to get started with this powerful tool for managing JavaScript dependencies.

Import maps

Introduced in the ECMAScript proposal stage in 2019 and added to the ECMAScript standard in 2021, import maps offer a new way to manage JavaScript modules without the need for a build process.

Import maps allow you to map modules to URLs, enabling JavaScript modules to be loaded directly in the browser.

An example

The imports property maps module specifiers to URLs. You can use relative or absolute URLs for the module URLs, and define multiple mappings in an import map.

<script type="importmap">
  {
    "imports": {
      "my-module": "./mymodule.js",
      "another-module/": "./another-module/"
    }
  }
</script>

Packages

In JavaScript it's common to have packages consisting of multiple modules and files. In such cases, you can map all the files of a package to a single identifier.

<script type="importmap">
  {
    "imports": {
      "my-module": "./mymodule.js",
      "moment/": "https://cdn.jsdelivr.net/npm/moment@2.29.4/src/"
    }
  }
</script>
<script type="module">
  import moment from 'moment/moment.js'

  console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
</script>

Note that we're using a trailing / in the identifier to indicate that we want to map all the files of the package.

Remote sources

In this example, we're using import maps to import the Moment.js library from a remote source.

<script type="importmap">
  {
    "imports": {
      "moment": "https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.js"
    }
  }
</script>
<script type="module">
  import moment from 'moment'

  console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
</script>

Scoping

Import maps also allow you to define scoping for your module mappings. Scoping allows you to restrict the use of certain module mappings to specific parts of your application.

To define a scope, you can use the scopes property in your import map. The scopes property is an object that maps URL patterns to nested import maps.

<script type="importmap">
  {
    "imports": {
      "moment": "https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.js"
    },
    "scopes": {
      "/legacy/": {
        "imports": {
          "moment": "https://cdn.jsdelivr.net/npm/moment@2.18.1/moment.js"
        }
      }
    }
  }
</script>

In this example we have defined a scope for the /legacy/ path. For any modules loaded from this path we are importing an older version of Moment.js.

Multiple versions

As an alternative to scoping, you have the option to define multiple versions of the same package. This allows you to avoid being limited to a specific scope, but it does require modifying your imports.

<script type="importmap">
  {
    "imports": {
      "moment@2.29": "https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.js",
      "moment@2.18": "https://cdn.jsdelivr.net/npm/moment@2.18.1/moment.js"
    }
  }
</script>
<script type="module">
  import moment from 'moment@2.29'
  import momentLegacy from 'moment@2.18'
</script>

Can I use them already?

For prototyping and during development, import maps can be an excellent choice as they allow developers to quickly experiment with different libraries and packages without the need for a build process. This can be useful in the early stages of a project when you're exploring different options and need to move quickly.

It's important to note that import maps are still a relatively new technology and may not be suitable for all projects. However, they are supported in most recent versions of the major browsers: Chrome, Firefox, and Safari. You can refer to the Can I use import maps page for an up-to-date overview of browser support and any known limitations or considerations.

Compatibility

To ensure compatibility with older browsers, a polyfill called es-module-shims is available. This polyfill allows you to use import maps and other modern JavaScript module features in browsers that do not natively support them.

Plugins for your favorite frontend tools

To simplify the integration of import maps into your preferred frontend tools, there are dedicated plugins available for seamless usage:

Extra resources

Looking to delve deeper into import maps? Check out the following resources:


Upcoming events

  • Drupal CMS Launch Party

    Zoals sommigen misschien weten wordt op 15 Januari een nieuwe distributie van Drupal gelanceerd. Namelijk Drupal CMS (ook wel bekend als Starshot). Om dit te vieren gaan we op onze campus een klein eventje organiseren. We gaan die dag samen de livestream volgen waarbij het product gelanceerd wordt. De agenda is als volgt: 17u – 18u30: Drupal CMS livestream met taart 18u30 – 19u00: Versteld staan van de functionaliteiten 19u – 20u: Pizza eten en verder versteld staan van de functionaliteiten Laat ons zeker weten of je komt of niet door de invite te accepteren! Tot dan!

    | Coven of Wisdom Herentals

    Go to page for Drupal CMS Launch Party
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met het bouwen van schaalbare digitale ecosystemen of zit je vast in een props hell met React of in een ander framework? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en flexibele applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! πŸš€ 18:00 – πŸšͺ Deuren open 18:15 – πŸ• Food & drinks 19:00 – πŸ“’ Building a Mature Digital Ecosystem - Maarten Heip 20:00 – 🍹 Kleine pauze 20:15 – πŸ“’ Compound Components: A Better Way to Build React Components - Sead Memic 21:00 – πŸ™‹β€β™€οΈ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op het bouwen van digitale ecosystemen en het creΓ«ren van herbruikbare React componenten. Maarten deelt zijn expertise over het ontwikkelen van een volwassen digitale infrastructuur, terwijl Sead je laat zien hoe je 'From Props Hell to Component Heaven' kunt gaan door het gebruik van Compound Components. Ze delen praktische inzichten die je direct kunt toepassen in je eigen projecten. πŸ“ Waar? Je vindt ons bij iO Herentals - Zavelheide 15, Herentals. Volg bij aankomst de borden 'meetup' vanaf de receptie. 🎫 Schrijf je in! De plaatsen zijn beperkt, dus RSVP is noodzakelijk. Dit helpt ons ook om de juiste hoeveelheid eten en drinken te voorzien - we willen natuurlijk niet dat iemand met een lege maag naar huis gaat! πŸ˜‹ Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creΓ«ert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! πŸš€πŸš€ 18:00 – πŸšͺ Doors open to the public 18:15 – πŸ• Let’s eat 19:00 – πŸ“’ First round of Talks 19:45 – 🍹 Small break 20:00 – πŸ“’ Second round of Talks 20:45 – 🍻 Drinks 21:00 – πŸ™‹β€β™€οΈ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Overcoming challenges in Visual Regression Testing - Sander van Surksum, Pagespeed | Web Performance Consultant and Sannie Kwakman, Freelance Full-stack Developer How can you overcome the challenges when setting up Visual Regression Testing? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian WΓΌrthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup

Share