0

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!

Amy
  • 1
  • 1
  • 1
    Does this answer your question? ["Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6](https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import) – M - Aug 12 '20 at 00:48
  • I believe this [has already been answered before](https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import). You have to add the module type in your script tag: `` – M - Aug 12 '20 at 00:49
  • Thank you both for the replies! I did try to add the module type before asking this question. But I actually resolved the problem! I realized that I didn't install the package correctly. – Amy Aug 12 '20 at 01:08

1 Answers1

0

Resolved, I just found out it was because I installed the package incorrectly!

I included a downloaded three.js file in the directory from my previous attempt. That's why the installation didn't go through even though the terminal said successfully installed.

Amy
  • 1
  • 1
  • If you're going to answer your own question, please try to explain you solved your problem so others in the future can also benefit from it. – M - Aug 12 '20 at 01:23