Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Import maps to natively import JavaScript modules using bare names

Bundlers in JavaScript let you import JavaScript modules with their bare names. For instance, if you have installed Lodash using NPM, you can import it like so.

import _ from 'lodash';

As you can tell, you’re importing the module using its bare name lodash.

To use modules with bare names, you need to use a bundler like Webpack or Rollup since browsers were only able to import modules using relative paths.

But not anymore. You can now do this natively in browsers using “import maps”.

Essentially, import maps are a way to map bare module specifiers to URLs or related paths. So, if you have a module under /app/js/utils.js, you can map it to a bare name like so.

<script type="importmap">
{
  "imports": {
    "utils": "/app/js/utils.js"
  }
}
</script>

As you can tell, you need to use the importmap script tag to define the import map. And then, you need to specify the JSON object that maps the bare name to the URL or the path of the module in the imports property.

Note: You need to keep in mind that you need to declare the importmap script tag before any other script tags where you’re importing the modules using bare names.

Now, you can import the module using the bare name in module scripts like so.

<script type="module">
  import utils from 'utils';
</script>

This is pretty handy since you don’t have to specify relative paths to the modules anymore. You can just use the bare name and the browser will resolve the path for you.

Apart from this, you can also use import maps to map bare names to URLs on a CDN. For instance, if you want to use an ES module from a CDN, you can do so like below.

<script type="importmap">
{
  "imports": {
    "lodash": "https://cdn.skypack.dev/lodash"
    "react": "https://esm.sh/react"
  }
}
</script>

You can then import them like how you would be used to import them using bundlers.

import _ from 'lodash';
import React from 'react';

The browser support for import maps is also pretty good now that import maps have recently landed in Safari Technical Preview. This means you can use import maps in all the major browsers now.

Here’s the browser support for import maps as of now.

Data on support for the import-maps feature across the major browsers from caniuse.com

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?