包含“THREE”和“three”的JavaScript importmap
我在引入一些JavaScript库,其中有些把three.js称为 "THREE",有些则称为 "three"。我加了一个importmap来尝试理清,但JS似乎不起作用,最终报错。
下面是在HTML文档头部的importmap。
<script type="importmap">
{
"imports": {
"THREE": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.min.js",
"three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.min.js"
}
}
</script>
下面是在HTML文档主体开头加载的脚本。
<script type="module">
import {Vector3} from "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.min.js"
import {ConvexGeometry} from "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/geometries/ConvexGeometry.js"
import * as EffectComposer from "https://cdn.jsdelivr.net/npm/[email protected]/examples/js/postprocessing/EffectComposer.js"
</script>
注意,ConvexGeometry 使用的是 "three" ,而 EffectComposer 使用的是 "THREE"。
在importmap中,如果我先写 "THREE" 再写 "three",它会抱怨 EffectComposer 找不到 "THREE"。如果把 "THREE" 与 "three" 的顺序对调,错误仍然一样。如果我移除对 "three" 的引用,似乎能走得更远,但随后在 EffectComposer 中又抱怨缺少 "three"。
是不是有什么技巧,或者我忽略了什么?正确的做法是什么,才能让它工作?
解决方案
你的问题来自两个简单的错误:
- 你通过使用完整URL来导入,绕过了import map。
- 你混用了不同版本的Three.js(
0.183.2和0.128.0)。
examples模块必须使用与核心库相同的版本。
要解决你的问题:使用一个版本,并通过import map的名称来导入,而不是使用完整的URL。
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",
"three/examples/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"
}
}
</script>
<script type="module">
import { Vector3 } from "three";
import { ConvexGeometry } from "three/examples/geometries/ConvexGeometry.js";
import { EffectComposer } from "three/examples/postprocessing/EffectComposer.js";
console.log(Vector3);
</script>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。