Cannot import examples: "SyntaxError: Cannot use import statement outside a module"

I’m unable to use examples from three.js as described here. Importing from three like

import { Mesh } from 'three'

works fine, however e.g.

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

always returns

Uncaught C:\Users\[...]\Documents\JavaScript\electron-setup\node_modules\three\examples\jsm\loaders\GLTFLoader.js:9
import {
^^^^^^

SyntaxError: Cannot use import statement outside a module

How do I solve this?

I’m trying to make it run on electron. I’m using the boilerplate code from electron-boilerplate.

/cc

1 Like

Turns out it was a bad boilerplate. Switching to electron-forge solved the problem.

1 Like

I suggest you delete your post at stackoverflow. Or provide an answer as well like here.

This error can happen in different cases depending on whether you’re working with JavaScript on the server-side with Node.js , or client-side in the browser. There are several reasons behind “Cannot use import statement outside a module” error, and the solution depends on how you call the module or script tag.

Add type=“module” inside the script tag

When working with ECMAScript modules and JavaScript module import statements in the browser, you’ll need to explicitly tell the browser that a script is module. To do this, you have to add type=“module” onto any ‹script› tags that point to a JavaScript module. Once you do this you can import that module without issues.

<script type="module" src="./index.js"></script>

If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property “type”: “module” as shown below.

{
  // ...
  "type": "module",
  // ...
}