脚本类型 importmap 的用途是什么?

Igo*_*Tot 13 javascript import

什么是<script type="importmap">以及为什么我突然需要它才能使我的代码正常工作?

<script type="importmap">
    {
        "imports": {
            "three": "https://example.com/3dstuff/three.module.js"
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

以前,我只写这个,Three.js 就可以工作,但现在如果没有 importmap,这部分就无法工作:

<script type="module"> import * as THREE from "https://example.com/3dstuff/three.module.js";
Run Code Online (Sandbox Code Playgroud)

小智 15

代码中的 importmap 本质上是设置从字符串“三”到实际 .js 文件 URL 的快捷方式。您应该在您的文件中写入内容<script type="module">import * as three from "three";并且由于您之前定义的导入映射,它将自动解析为 URL。

来自https://github.com/WICG/import-maps

通过向浏览器提供以下导入映射

<script type="importmap">
{
  "imports": {
    "moment": "/node_modules/moment/src/moment.js",
    "lodash": "/node_modules/lodash-es/lodash.js"
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

上面的行为就好像你写了一样

import moment from "/node_modules/moment/src/moment.js";
import { partition } from "/node_modules/lodash-es/lodash.js";
Run Code Online (Sandbox Code Playgroud)