
通过unpkg引入three.js的解决方案
问题描述:如何在不使用框架的情况下通过unpkg引入three.js?
相关代码:
<!-- index.html -->
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.155.0/build/three.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
console.log(THREE);
</script>// main.js
console.log("Hello Three.js")
console.log("js" + THREE)
const scene = new THREE.Scene();问题现象:
在main.js中无法识别THREE,报错:"main.js:2 Uncaught ReferenceError: THREE is not defined at main.js:2:20"
解决方案:
有两种解决办法:
方案一:
将main.js的类型改为module并直接在其中书写代码。
<!-- index.html -->
<script type="module">
import * as THREE from 'three';
console.log(THREE);
console.log("Hello Three.js");
console.log("js" + THREE);
const scene = new THREE.Scene();
</script>方案二:
将main.js中的代码移至index.html中,并将main.js的类型改为module。
<!-- index.html -->
<script type="module">
import * as THREE from 'three';
console.log("Hello Three.js");
console.log("js" + THREE);
const scene = new THREE.Scene();
</script>
<script type="module" src="./main.js"></script>










