JavaScript import maps are now supported cross-browser

With import maps, importing ES modules now becomes a lot better.

ES modules are a modern way to include and reuse JavaScript code in web applications. They are supported by modern browsers and provide several benefits over older, non-modular approaches to JavaScript development.

A modern way to use ES modules is with the <script type="importmap"> tag. This tag allows you to define a mapping of external module names to their corresponding URLs, which makes it easier to include and use external modules in your code.

To use the <script type="importmap"> approach, you first need to add it to the <head> section of your HTML document. Inside the tag, you can define a JSON object that maps module names to their corresponding URLs. For example:

<script type="importmap">
  {
    "imports": {
      "browser-fs-access": "https://unpkg.com/browser-fs-access@0.33.0/dist/index.modern.js"
    }
  }
</script>

This code defines a single external module named "browser-fs-access" and maps it to the URL of the browser-fs-access library, hosted on the unpkg CDN. With this mapping in place, you can now use the import keyword to include the browser-fs-access library in your code. Note that the import keyword is only available inside a script tag with the type="module" attribute.

<button>Select a text file</button>
<script type="module">
  import {fileOpen} from 'browser-fs-access';

  const button = document.querySelector('button');
  button.addEventListener('click', async () => {
    const file = await fileOpen({
      mimeTypes: ['text/plain'],
    });
    console.log(await file.text());
  });
</script>

Using the <script type="importmap"> tag and the import keyword provides several benefits over older, non-modular approaches to JavaScript development. It allows you to clearly and explicitly specify the external modules your code depends on, which makes it easier to understand and maintain your code. Overall, using ES modules with the <script type="importmap"> tag is a modern and powerful way to include and reuse JavaScript code in web applications. You can feature-detect support as follows:

if (HTMLScriptElement.supports('importmap')) {
  // The importmap feature is supported.
}

Browser Support

  • 89
  • 89
  • 108
  • 16.4

Further reading

Part of the Newly interoperable series