Hi,
I’m trying to use Vite to build a test project making use of a three.js based library (the library is my own).
My problem is that either I get the warning “Multiple instances of three.js being imported” or “THREE is not defined”, depending on where I import three.
This is more to do with Vite than three.js, but just raising it here in case anyone has had the same problem. I can see similar previous topics, but they don’t seem to be exactly the same as my case:
Here is what I have tried:
- if I do an
import * as THREE from 'three'
in both my library and my test app, I get the “multiple instances of Three.js” warning. - if I leave out the imports from EITHER the library OR the test app, I get a
THREE is not defined
error.
Here is my test app:
import * as THREE from 'three';
import * as MyLib from '../../mylib/lib/main.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth/window.innerHeight, 0.001, 100);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", e => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
const box = new THREE.BoxGeometry(2,2,2);
const cube = new THREE.Mesh(box, new THREE.MeshBasicMaterial({ color: 0xff0000 }));
scene.add(cube);
const mylib = new MyLib(scene, camera);
renderer.setAnimationLoop(animate);
function animate() {
mylib.update();
renderer.render(scene, camera);
}
I use a standard Vite config (no changes). package.json
of the app is very simple, just specifies three as a dependency and vite as a dev dependency.
The same behaviour occurs when I build my lib as a Rollup bundle through Vite, excluding three.js from the bundle.
Any ideas? It seems to be difficult to only import three.js once; either it’s imported twice or not at all.
EDIT: vite in dev mode does not have the same problem. vite in dev mode uses esbuild, not Rollup - suggesting it’s a Rollup issue specifically.
Sorry if it’s more to do with build tools than three itself, but just asking in case anyone has encountered the same problem.
Thanks.