无法使用 Three.js 导入 OrbitControls.js

Mic*_*RSF 4 javascript

我正在查看 Three.js,并找到了这个示例。 https://trijsfundamentals.org/thirdjs/lessons/thirdjs-load-gltf.html 不幸的是,当我使用 Flask 在本地运行它时,我一直收到所有三个导入的错误。

import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/build/three.module.js';
import {OrbitControls} from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/examples/jsm/loaders/GLTFLoader.js';
Run Code Online (Sandbox Code Playgroud)

Uncaught SyntaxError: Cannot use import statement outside a module

我到处寻找解决方案,但找不到任何解决方案。

我还尝试使用脚本标签运行三个导入。

<script src="{{url_for('static',filename='js/three/build/three.js')}}"></script>
<script type="module" src="{{url_for('static',filename='js/three/examples/jsm/controls/OrbitControls.js')}}"></script>
<script type="module" src="{{url_for('static',filename='js/three/examples/jsm/loaders/GLTFLoader.js')}}"></script>
Run Code Online (Sandbox Code Playgroud)

这可行,但是当我尝试下面的代码时,我得到: Uncaught ReferenceError: OrbitControls is not defined

const controls = new OrbitControls(camera, canvas);
controls.target.set(0, 5, 0);
controls.update();
Run Code Online (Sandbox Code Playgroud)

另外,如果我尝试使用 GLTFLoader,我会收到错误。

const loader = new THREE.GLTFLoader();
Run Code Online (Sandbox Code Playgroud)

或者

const loader = new GLTFLoader();
Run Code Online (Sandbox Code Playgroud)

任何想法我如何解决这个问题将不胜感激。

gai*_*tat 6

您需要说明您的脚本标记的类型为module。所以你需要的是这样的:

<html>
  <body>
    <script type="module">
      import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/build/three.module.js';
      import {OrbitControls} from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/examples/jsm/controls/OrbitControls.js';
      import {GLTFLoader} from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/examples/jsm/loaders/GLTFLoader.js';
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)