如何通过unpkg引入three.js?

作者站长头像
站长
· 阅读数 8

问题描述

three.js新手,我没有起前端框架,想通过unpkg引入简单的试一下demo。参考官网给的安装方式Option 2: Import from a CDNindex.html内引入three.js,业务代码在main.js。main.js中无法识别THREE。

相关代码

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Basic Scene</title>
  <!-- 引入three.js -->
  <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>
</head>
<body>
  <script src="./main.js"></script>
</body>
</html>

main.js

console.log("Hello Three.js")
console.log("js" + THREE)
const scene = new THREE.Scene();

你期待的结果是什么?实际看到的错误信息又是什么?

我希望能够在main.js中识别THREE,并且创建一个scene。目前看到的报错是:

main.js:2 Uncaught ReferenceError: THREE is not defined at main.js:2:20

谢谢围观和帮助!

回复
1个回答
avatar
test
2024-06-28
<!-- 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>

或者:index.html

<script type="module" src="./main.js"></script>

main.js:

import * as THREE from 'three';

console.log("Hello Three.js");
console.log("js" + THREE);
const scene = new THREE.Scene();
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容