I am currently delving into the world of three.js and working on my first project. I am following the example code provided on the three.js website. Everything runs smoothly when I have three.js stored in a folder like:
js/ directory
However, I am encountering issues when trying to import it as a module. I am installing the module using:
npm i three
Then running it as a local server by installing:
npm install http-server -g
and launching my file test.html on port: 8000
http-server . -p 8000
Below is the complete content within the body tag:
<body>
<script>
import * as THREE from 'three';
const scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
var animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
</script>
</body>
Why am I unable to import the module? The browser displays this error message:
Uncaught SyntaxError: Cannot use import statement outside a module