DEV Community

Cover image for JavaScript Import Map
Amin
Amin

Posted on

JavaScript Import Map

An import map is a special type of script tag that can be used to modify the resolution of modules imported using ECMAScript Modules in your HTML page by the browser.

An Import Map is written in the JSON format syntax.

{
  "imports": {
    "utility": "./path/to/utility.js",
    "event": "./path/to/event.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

You can define an Import Map in any HTML document by using the script tag and with the type importmap.

<script type="importmap">
  {
    "imports": {
      "utility": "./path/to/utility.js",
      "event": "./path/to/event.js"
    }
  }
</script>
Enter fullscreen mode Exit fullscreen mode

And you can then use the keys as names for your imports in your scripts.

<script type="module">
  import { something } from "utility"
  import { EventEmitter } from "event"
</script>
Enter fullscreen mode Exit fullscreen mode

Instead of the traditional

<script type="module">
  import { something } from "./path/to/utility.js"
  import { EventEmitter } from "./path/to/event.js"
</script>
Enter fullscreen mode Exit fullscreen mode

Note that by default, only the following are considered valid URLs to import from by the ECMAScript Module standard.

  • Relative URL
  • Absolute URL
  • HTTP URL

And the following are considered violations.

  • Node Module
  • Relative URL without extension
  • Absolute URL without extension

The Import Map specification allows us to bypass these limitations. The downside of it being that you have to manually provide the relative, absolute or HTTP URLs for each imported module that do not follow the above rules.

<script type="importmap">
  {
    "imports": {
      "preact": "./node_modules/preact/dist/index.js",
      "preact-page": "./node_modules/preact-page/dist/index.js"
    }
  }
</script>
<script type="module">
  import { render } from "preact"
  import { PageProvider } from "preact-page"
</script>
Enter fullscreen mode Exit fullscreen mode

Or even from HTTP URLs.

<script type="importmap">
  {
    "imports": {
      "preact": "https://unpkg.com/preact?module",
      "preact-page": "https://unpkg.com/preact-page?module"
    }
  }
</script>
<script type="module">
  import { render } from "preact"
  import { PageProvider } from "preact-page"
</script>
Enter fullscreen mode Exit fullscreen mode

Note that this can also be used to resolve folders in order to simplify the writing of long and tedious relative or absolute URLs.

<script type="importmap">
  {
    "imports": {
      "@utilities/": "../../../path/to/utilities/"
    }
  }
</script>
<script type="module">
  import { stringify } from "@utilities/string.js"
</script>
Enter fullscreen mode Exit fullscreen mode

If you have reach this part of the article and want to know more, check out the official documentation here.

Top comments (0)