Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's script type importmap used for?

What is <script type="importmap"> and why do I suddenly need it for my code to work?

<script type="importmap">
    {
        "imports": {
            "three": "https://example.com/3dstuff/three.module.js"
        }
    }
</script>

Before, I would just write this and Three.js would work, but now this part doesn't work without the importmap:

<script type="module"> import * as THREE from "https://example.com/3dstuff/three.module.js";
like image 989
Igor Tot Avatar asked Jan 01 '26 19:01

Igor Tot


2 Answers

The importmap in your code is essentially setting up a shortcut from the string "three" to the actual .js file URL. What you should be writing in your <script type="module"> is import * as three from "three"; and it will automatically resolve to the URL due to the importmap you defined before.

From https://github.com/WICG/import-maps:

By supplying the browser with the following import map

<script type="importmap">
{
  "imports": {
    "moment": "/node_modules/moment/src/moment.js",
    "lodash": "/node_modules/lodash-es/lodash.js"
  }
}
</script>

the above would act as if you had written

import moment from "/node_modules/moment/src/moment.js";
import { partition } from "/node_modules/lodash-es/lodash.js";
like image 110
ps4star Avatar answered Jan 03 '26 07:01

ps4star


Import maps will allow you to both import external code into your project without a build tool and it will only load the code when it is needed at runtime. Import maps won’t completely replace build tools that perform many other valuable actions like building style sheets and handling images, but they will allow you to bootstrap new JavaScript applications quickly and easily using only the native browser functionality

like image 22
Sourabh Ranka Avatar answered Jan 03 '26 08:01

Sourabh Ranka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!