如何通过unpkg引入three.js?

问题描述

three.js新手,我没有起前端框架,想通过unpkg引入简单的试一下demo。
参考官网给的安装方式Option 2: Import from a CDN
index.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

谢谢围观和帮助!

阅读 2.7k
1 个回答
<!-- 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();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题