BUG: Import statements in example/jsm examples are broken

There is a wired bug where if you use the example/jsm modules as a standalone with/without three.module.js it shows this error:

TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".
    at /

At first, I thought it was my code but after some testing and looking around, I found this as the possible culprit.

import {
	EventDispatcher,
	Quaternion,
	Vector3
} from 'three';

I think what is happening is that the import statement tries to get the “three” module when it does not exist even though the module.js does.

I try to fix this by changing the import statement to reference three.module.js and it works!

modules/FlyControls.js

import {
	EventDispatcher,
	Quaternion,
	Vector3
} from './three.module.js';

script.js

import { FlyControls } from "../modules/FlyControls.js"

console.log(FlyControls)

output / console

Function {}

I’m not sure how to fix this for the library as a whole as I’m a BIG NOOB when it comes to modules and I consider myself okay at javascript.

Here are the MREs:

Finally, my live code:

The standard way to import three.js (or most JS libraries) is to use NPM and a build tool, such as Parcel, Vite, or Webpack. These will resolve imports from the three namespace automatically, with no changes required. That’s what I do for all projects.

If you’d rather use static files and no build system, the next best thing is probably import maps, which allows the browser to figure out how to import from ‘three’. To support all browsers you’ll need a polyfill, most of the official three.js demos have examples of this:

… other than those two approaches, changing all the references from ‘three’ to `three.module.js’ is an option, just not an option I’d tend to recommend. :slight_smile:

2 Likes

I am actually going to use NPM for publishing, but for prototyping, I’m using static stuff as it is easier to handle in repl.it

thank you for the answer. :+1:

1 Like