liveBook · Manning

Import map

As explained in Secrets of the JavaScript Ninja, Third Edition

An import map is a JSON mapping that associates JavaScript module specifiers with URLs or paths.

What should a browser do with `import "esm-ninja"`? The name is a bare module specifier, not a path or URL. ECMAScript leaves specifier resolution to the runtime; an import map tells the browser where that name points. section 13.1.2

Listing 13.13 Defining an import map in HTML
<html>
  <head>
    <title>ESM Ninja</title>
    <script type="importmap"> #A
      { #A
        "imports": { #A
          "esm-ninja": "/assets/esm-ninja.js" #A
        } #A
      } #A
    </script> #A
    <script #B
      type="module" #B
      src="/assets/app.js" #B
    ></script> #B
  </head>
  <body>
    <p>Loading...</p>
  </body>
</html>

The HTML places a JSON map in `<script type="importmap">`. Its `imports` entry maps `esm-ninja` to `/assets/esm-ninja.js` before the module script loads. section 13.1.2

With that map, the module can write `import "esm-ninja"` rather than the asset path. Node.js handles a similar-looking bare import differently: it searches for a package and uses its `package.json` entry points. The spelling alone does not determine how an import resolves; the runtime does. section 13.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through an HTML import map and matching bare import, without showing advanced mapping rules.
Examples
Shows `esm-ninja` mapped to `/assets/esm-ninja.js` and imported by name.
What you can do after
Operate/configure it to resolve a bare import in a browser module.
How it connects
Connects import maps to ESM module specifiers, browser module scripts, and Node.js package entry points.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.