What's script type importmap used for?
Asked Answered
I

2

14

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";
Immingle answered 29/1, 2022 at 6:29 Comment(0)
C
16

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";
Crispation answered 29/1, 2022 at 12:45 Comment(3)
Thanks for the answer! Is this something new? Because few days ago my code worked without importmap, and suddenly just logged a console error without any changes... Probably due to Three.js update.Immingle
@IgorTot <script type="importmap"> is a new feature to the W3 spec, so it's possible that Three.js adopted it/required its users to include it to use Three.js. But looking at the mechanics of it, I don't see any reason why you would have to set up an importmap to be able to use Three, since it's just a shortcut to the full URL anyway. There might be something I don't understand about it. If you're really curious you should just read through the github page linked in my answer, it seems to have all the up-to-date info.Crispation
how do i ensure the importmap is executed before the module when the module is preloaded via modulepreload??? this Q is also to @CrispationJestinejesting
P
2

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

Professionalize answered 11/4, 2023 at 4:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.