Cannot use import statement outside a module

I’m trying to set up a simple Template for thee js but I get:

“Cannot use import statement outside a module”

My index.html:

    <body>
    <div id= "container" ></div>
        <script src="app.js"></script>
</body>

And in app.js I do:

 import * as THREE from './js/three.module.js';
    export default class Sketch{

        constructor(){

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

            this.camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
            this.camera.position.z = 1;
            this.scene = new THREE.Scene();
            this.addMesh();
            this.render();
        }

        addMesh(){

            this.geometry = new THREE.PlaneBufferGeometry( 10, 10 );
            this.material = new THREE.MeshNormalMaterial({side: THREE.DoubleSide});
            this.mesh = new THREE.Mesh( this.geometry, this.material );
            this.scene.add( this.mesh );
            
        }

        render(){

            this.time++;
            this.mesh.rotation.x += 0.01;
    	    this.mesh.rotation.y += 0.02;
            console.log(this.time);
            this.renderer.render( this.scene, this.camera );
            window.requestAnimationFrame(this.render.bind);
        }
    }
    new Sketch();

What am I doing wrong?
Thanks in advance.

If you are using ES6 import/export statements in your code, you can’t import it via the above statement. Try to put your entire code from app.js into the following tag:

<script type="module">

    // JS code

</script>
1 Like

Thanks, I was using this method before, everything in the index.html but I’m trying to get a cleaner code.
Also, when I put everything inside the tag I get:

Failed to load module script: The server responded with a non-JavaScript MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.

if you are using .babelrc to configure babel, look at the issue:
transformIgnorePatterns setting doesn't work when using a .babelrc instead of babel.config.js · Issue #10256 · jestjs/jest · GitHub

and use transformIgnorePatterns: ['/node_modules/(?!(three)/)'], in your jest config file

I had this problem some days ago. I solved using:

<script type="importmap">
			{
				"imports": {
					"three": "https://cdn.jsdelivr.net/npm/three@0.131/build/three.module.js"
				}
			}
</script>
<script type="module" src="./index.js"></script>

You need to write type=module and put a ./ before app.js. Besides, if you import using the “imports” you need to place it before the app.js script tag. It worked for me.