'Three.js Uncaught Syntax error : Cannot use import statement outside a module
I'm trying to implement a 3d design file (gltf) into a website with three.js and I'm keeping having this error:
Here is the html/Javascript/CSS code :
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8 />
<link rel="stylesheet" type="text/css" href="test2.css" />
</head>
<body>
<script src="../three_import/three.min.js"></script>
<script src="../three_import/OrbitControls.js"></script>
<script src="../three_import/GLTFLoader.js"></script>
<script>
let scene, camera, renderer;
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xdddddd);
controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', renderer);
hlight = new THREE.AmbientLight (0x404040,100);
scene.add(hlight);
let loader = new THREE.GLTFLoader();
loader.load('../Image/USB.gltf', function(gltf){
car = gltf.scene.children[0];
car.scale.set(0.5,0.5,0.5);
scene.add(gltf.scene);
animate();
});
}
function animate() {
renderer.render(scene,camera);
requestAnimationFrame(animate);
}
init();
</script>
</body>
</html>
I have no idea what this error could come from, and I've tried everything given in othersites and it doesn't work.
Thank you
Solution 1:[1]
Well, this is true: Your main script tag is of type text/javascript, not module.
In your HTML, you don't need:
<script src="../three_import/three.min.js"></script>
<script src="../three_import/OrbitControls.js"></script>
<script src="../three_import/GLTFLoader.js"></script>
Instead, you would do this to your main script tag:
<script type="module">
import * as THREE from '../three_import/three.min.js';
import {OrbitControls} from '../three_import/OrbitControls.js';
import {GLTFLoader} from '../three_import/GLTFLoader.js';
//Your code here
</script>
Remember, since we are doing this, instead of doing new THREE.OrbitControls() or new THREE.GLTFLoader(), we would use new OrbitControls() and new GLTFLoader(). (without the THREE)
That's all!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anye |

