0

Attempting to run a nodejs Express server with ES6 imports (for three.js). But I am getting the error despite adding "type:module" to the package.json and running the server with --experimental-modules app.js. My version of node is 12.16.3.

Uncaught SyntaxError: Cannot use import statement outside a module index.js.1

I've also tried using the .mjs file extension too, with no success.

Here is the code inside app.js

import express from 'express';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
let app = express();




const __dirname = dirname(fileURLToPath(import.meta.url));

//setting middleware
app.use(express.static(__dirname + '/public')); //Serves resources from public folder

var server = app.listen(5000);

and index.js

import * as THREE from 'three.module.js';

var camera, scene, renderer;
var geometry, material, mesh;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 1;

    scene = new THREE.Scene();

    geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
    material = new THREE.MeshNormalMaterial();

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.02;

    renderer.render( scene, camera );

}

any idea why I am getting getting this errror? Would it be a better idea to just use the Current Node 14 instead of LTS?

SpikeThea
  • 340
  • 1
  • 3
  • 13
  • 1
    *"My version of node is 12.16.3."* Just for what it's worth, you no longer need the flag in v13, and in v14 you no longer get the *"The ESM module loader is experimental"* warning. Worth upgrading if you can. – T.J. Crowder May 16 '20 at 17:38
  • 2
    Node.js and its config, etc., are irrelevant -- `index.js` is being used **in the browser**, not in Node.js. You need to include it in the HTML using `type="module"`, see the answers to the linked question for details. – T.J. Crowder May 16 '20 at 17:41

0 Answers0