JavaScript importmap 导入模块

复习 .html 文件中导入模块

从 JavaScript ES6 模块化:import和export 中,可知 .html 文件导入模块的方式如下:

<script type="module">
    // 从js文件中导入要用的变量、函数
    // 注意:必须有 ./ ,否则报错。.js 不能省略
    import * from './js/loadash.js'
</script>

提出问题

在 html 文件中导入模块,必须在 from 后面写 路径,如上代码

那么,如何在 .html 文件中导入模块,可以像 node.js 那样:from 后面 不指定路径

from 后为什么要指定路径

必须指定路径,因为:浏览器 不知道从哪里加载 模块

node环境

在 Node.js 环境下, 不用指定路径,如下:

import * from 'loadash';

在 .html 文件中不指定路径的好处

这样在 .html 中的写法,就可以与 node.js 环境完全相同

解决

使用 importmap

importmap

第一步

使用 Json 的形式来定义浏览器中的全局模块:

<script type="importmap">
{
    "imports": {
        "three": "./js/three.module.js"
    }
}
</script>

第二步

有了上面的 importmap 定义, 可以在 .html 中 import 时,from 后面不指定路径:

<script type="module">
    import * as THREE from 'three';
    // 浏览器控制台测试,是否引入成功
    console.log(THREE.Scene);
</script>

参考:
https://beginor.github.io/2021/08/16/using-es-modules-in-borwser-with-importmaps.html
https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/script/type/importmap
https://segmentfault.com/a/1190000042261401


原文出处:/show_1IX8cPJVSrsF.html