I am currently exploring the integration of Three.js into an Angular application.
Following the documentation, I imported Three.js using the following line: import * as THREE from 'three';
In addition, I installed the types for Three.js with the command npm install @types/three --save
.
The issue arises when attempting to load models using the OBJLoader2.
According to the official example, the correct way to instantiate the OBJLoader2 is via
var loader = new THREE.OBJLoader2();
. However, this class is not defined directly in the 'three' module but rather in 'three/examples/js/loaders/OBJLoader2.js'.
After many unsuccessful attempts to import the file, including a naive approach like
import '../../node_modules/three/examples/js/loaders/OBJLoader2.js';
, the browser console returned an error:
OBJLoader2.js:8 Uncaught ReferenceError: THREE is not defined at eval (OBJLoader2.js:8) at Object.../../../../three/examples/js/loaders/OBJLoader2.js (vendor.bundle.js:430)
The content of the file 'OBJLoader2.js' makes it clear that it expects THREE to be globally defined, which leads to the runtime error due to scoping issues.
Prior to importing the file, I attempted to declare THREE globally in various ways:
declare var THREE;
or
declare global{
interface Window{THREE:any;}
}
import * as THREE from 'three';
window.THREE = THREE;
While these declarations resolved the initial error, a subsequent error occurred when attempting to use the loader:
var loader = THREE.OBJLoader2();
loader.load('assets/untitled1.obj', callbackOnLoad, null, null, null, false);
This resulted in the error:
ERROR TypeError: Cannot read property 'load' of undefined at AppComponent.initCube (app.component.ts:52)
Despite extensive online research, I have been unable to find a solution or similar experiences documented. Any assistance on resolving this challenge would be greatly appreciated. Thank you in advance.