Reputation: 1223
var THREE = require('three');
require('three/examples/js/loaders/OBJLoader.js');
After I require threejs from node_modules I decided to use the OBJLoader they provide, however I get an unexpected error.
THREE is not defined
at eval (eval at <anonymous> (experiment.js:133), <anonymous>:5:1)
Inside the OBJLoader:
THREE.OBJLoader = function ( manager )
it tells me the Three inside the OBJLoader is not defined although i required it just above. What should I do when trying to require files this way?
Upvotes: 2
Views: 12492
Reputation: 6986
Due to three.js and especially the code from it's examples relying on the global variable THREE
being defined, it is a bit complicated to use those with browserify and the likes.
What I mostly did in browserify-projects was to create a file three-loader.js
that looks like this:
const THREE = require('three');
// make three available for files from examples
window.THREE = THREE;
// load stuff from examples
require('three/examples/js/loaders/OBJLoader.js');
module.exports = THREE;
And everywhere in the project use const THREE = require('./three-loader');
instead of require('three');
.
Another option is to copy the files from the examples folder into your project and add a line const THREE = require('three');
to the top of these files.
Upvotes: 3
Reputation: 6706
The file three/examples/js/loaders/OBJLoader.js
is not meant to be require'd - there is no module.exports
. It is still possible require
the file as you are doing, however it will just try to execute the code in the context of that file - and in the context of that file there is no variable THREE
defined. The file in question was designed to be loaded in the browser where a window/global variable THREE was defined.
Three.js is a client-side library - to load in browser you can use a script tag:
<script src="js/three.min.js"></script>
That will establish a variable THREE
in your browser, so that you can then load the example OBJLoader.js via:
<script src="js/OBJLoader.js"></script>
Upvotes: 0
Reputation: 887
It's because you're trying to load a node module that has not been installed. Sometimes too, other dependencies associated with the module haven't been installed and can cause it to fail. If I were you, I would head over to npm and just do npm install three
and then require it in with var three = require('three');
.
Link on npm: https://www.npmjs.com/package/three
Edit: The error you listed means that the module is not being found at all, that's why I think it's more to do with the path you're including and maybe other dependencies as well. NPM install will fix everything usually. And then to use the method on the object you require in, just do your standard dot notation
Upvotes: -1