Skip to main content

Picture of Patrick's face
Jump to about Patrick Grey

Patrick Grey

Web developer, e‑learning specialist & master of disguise

Import maps

Published: 16 February 2025

Today I want to try using import maps. The end goal is to be able to remove Vite from my build process and simplify things. Reducing dependencies is always satisfying to me.

Bonus extra task is to see if I can integrate a JavaScript package from NPM or UNPKG.

What are Import Maps? Mozzilla gives us some detail.

I've had trouble using them at work, I think mainly due to problems with relative paths but also the error messages you get aren't that helpful i.e. I keep getting:

Uncaught TypeError: Failed to resolve module specifier "module1". Relative references must start with either "/", "./", or "../"

Plan

  1. Get one JS file to load another simple one.
  2. Make a loading chain
  3. Call one file from multiple other files
  4. Call a package

Fails

Here is my initial setup that didn't work.

<script type="module" src="./js/index.js"></script>
    <script type="importmap">
    {
        "imports": {
            "module1": "./js/packages/module1.js"
        }
    }

    </script>

I take the relative URL from the index page. This results in the error noted above.

<script type="module" src="./js/index.js"></script>
    <script type="importmap">
        {
            "imports": {
                "module1": "./packages/module1.js"
            }
        }
    </script>

I take the relative URL from the javascript file. This still results in the error noted above.

What I was doing wrong was loading my script before the import map is created. Seems obvious now 😅. Links are relative to the HTML page. Now the scripts load as expected.

So, this works:

<script type="importmap">
        {
            "imports": {
                "module1": "./js/packages/module1.js"
            }
        }
    </script>
<script type="module" src="./js/index.js"></script>

I want to be able to develop offline (the joys of wifi in rural Scotland). UNPKG seems a good start but not for all the files I need if offline. I need to investigate further and will update this post if I get anywhere.

I found this article very useful: https://www.honeybadger.io/blog/import-maps/