最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What's script type importmap used for? - Stack Overflow

programmeradmin6浏览0评论

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

<script type="importmap">
    {
        "imports": {
            "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 ".module.js";

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";
Share Improve this question edited Feb 4, 2022 at 14:05 Nimantha 6,4716 gold badges30 silver badges76 bronze badges asked Jan 29, 2022 at 6:29 Igor TotIgor Tot 1751 silver badge9 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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";

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

发布评论

评论列表(0)

  1. 暂无评论