Search code examples
javascriptthree.jsrequire

require not working as expected


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?


Solution

  • 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.