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

  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte 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 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. 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
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design
  • The Leadership Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! 🚀 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: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Leadership Meetup

Share