hasanbaghal
hasanbaghal

Reputation: 25

javascript `require` instead of html `script` at three.js file in node.js

I use javascript require instead of html script at three.js file in node.js. a section of html file:

<script src="../build/three.js"></script>

<script src="js/controls/DragControls.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/controls/TransformControls.js"></script>

<script src="js/libs/stats.min.js"></script>
<script src="js/libs/dat.gui.min.js"></script>

an equivalent section of javascript file:

var THREE = require('../build/three.js')

//module.exports = THREE

THREE.DragControls = require('./js/controls/DragControls.js')
THREE.OrbitControls = require('./js/controls/OrbitControls.js')
THREE.TransformControls = require('./js/controls/TransformControls.js')

var Stats = require('./js/libs/stats.min.js')
var dat = require('./js/libs/dat.gui.min.js')

so the browserify command show blank page in the browser.I think maybe the codes in javascript js file are not correct.so what should I do?

Upvotes: 0

Views: 6532

Answers (1)

Martin Schuhfu&#223;
Martin Schuhfu&#223;

Reputation: 6986

The problem with using browserify together with three.js is this:

  • three.js uses the global variable THREE as it's namespace, when you require('three') (assuming you did npm install three), this global object will be returned, so var THREE = require('three'); pretty much does what you'd expect.
  • the three.js extensions mostly don't return (via module.exports if available) the Objects they defined, so in their case THREE.OrbitControls = require('...') will not do what you expect. Instead, they simply expect the global object THREE to exists and assign a new property to it. You will see a pattern of THREE.OrbitControls = function() {...} in these files.
  • this doesn't work, because three.js (the main library) will not assign itself to the window-object if there is module.exports for it to use (you can easily test this, just add a console.log(window.THREE).

To fix this, you just need to do this one step before loading the extensions, like this:

var THREE = require('three');

window.THREE = THREE;

require('./path/to/OrbitControls.js');
// ...

console.log(THREE.OrbitControls);

Upvotes: 4

Related Questions