I'm trying to import Three.js inside of my JavaScript file (not HTML script element), but I get an error "Uncaught SyntaxError: Cannot use import statement outside a module". My Three.js code works if I put it in a Script element in HTML but I want to use a canvas element to display the code from JavaScript file instead.
I've installed Three.js using NPM already and imported. I also used a canvas element in my html which I queried for in my JavaScript.
import * as THREE from 'three';
let scene, camera, renderer, geo, orbs, controls;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight);
controls = new THREE.TrackballControls(camera);
controls.addEventListener('change', render);
let canvas = document.querySelector("canvas");
renderer = new THREE.WebGLRenderer({
alpha: true,
canvas: canvas
});
I've tried declaring a const and requiring, as well as adding "type="module" to the script and that didn't work either.
I'm new to Three and I'm not sure if this is best practice because I've seen it being used in script tags more often than in a separate JS file.
Thank you!