程序开发 · 2023年11月11日

如何在不使用框架的情况下,通过 unpkg 引入 Three.js 并解决 main.js 中无法识别 THREE 的问题?

通过unpkg引入three.js的解决方案

问题描述:如何在不使用框架的情况下通过unpkg引入three.js?

相关代码:

<!-- index.html -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/[email protected]/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();

登录后复制

问题现象:

在mn.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>

登录后复制

以上就是如何在不使用框架的情况下,通过 unpkg 引入 Three.js 并解决 mn.js 中无法识别 THREE 的问题?的详细内容,更多请关注GTHOST其它相关文章!