通过 unpkg 引入 three.js
three.js 新手常常遇到通过 unpkg CDN 引入 three.js 时,无法识别 THREE 对象的困扰。本文将介绍如何解决该问题,让你顺利上手 three.js。
在 index.html 中,参考官网推荐的 Option 2,使用 es-module-shims 并定义 importmap 来引入 three.js:
<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>
登录后复制
然而,当你将代码转移到业务代码模块 mn.js 时,可能会发现无法识别 THREE。这是因为 main.js 还没有定义 import 语句。
以下有两种解决方法:
- 在 index.html 的 type=”module” 脚本标签中直接编写业务代码,无需额外的 main.js 文件。
- 在 index.html 中使用 type=”module” 的 script 标签导入 main.js:
<script type="module" src="./main.js"></script>
登录后复制
然后在 main.js 中添加 import 导入语句:
import * as THREE from 'three'; console.log("Hello Three.js"); console.log("js" + THREE); const scene = new THREE.Scene();
登录后复制
这样一来,你就可以在 main.js 中访问 THREE 对象,并创建三维场景。随着 you 添加更多代码 module types cript 不断研究 three.js 的世界。
以上就是通过 unpkg 引入 three.js 后,在 mn.js 中无法识别 THREE 对象?的详细内容,更多请关注GTHOST其它相关文章!