Module handling in Phaser
We have stumbled into some problems when using require to include Phaser.
Consider the following example:
var Phaser = require("phaser/dist/phaser-no-physics");
Doing this will cause a ReferenceError (PIXI is not defined) originating from Circle.js:
// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
PIXI.Circle = Phaser.Circle;
The reason why this happens is because Phaser uses function scopes to make sure variables don't leak into the global scope. A really simple code extract to visualize this:
(function () {
var PIXI = { ... };
module.exports = PIXI;
}).call(this);
(function () {
var Phaser = { ... };
PIXI.Circle = Phaser.Circle; // <--- This will fail since PIXI isn't globally defined
}).call(this);
With Phaser 2.3 we simply did
window.PIXI = require("phaser/dist/modules/pixi");
var Phaser = require("phaser/build/custom/phaser-no-physics");
to circumvent this. But this isn't optimal since it causes PIXI to be defined twice. And in Phaser 2.4 there doesn't seem to exists a PIXI bundle anymore.
I've solved this hackishly in a fork: https://github.com/mkristo/phaser/commit/6d742155bf5fdb93a9593755a3e718344b5b5bfe
I didn't want to create a pull request for this since it is so ugly. :blush: But it solves the problem, and if you want I can create a pull request for it.
The best way of solving this imho would be to use require internally in Phaser, instead of creating bundles using concatenation of files. This would require a bigger refactoring though.
2.4 uses an almost identical Pixi bundle as 2.3 does, it just has a couple less files in it that have moved into Phaser fully (like PIXI.Text) and some internal bug fixes, but is otherwise the same. So whatever you were doing for 2.3 should, theoretically, carry on with 2.4 in the same way.
There are no plans to change Phaser 2 to use requireJS at all, structurally Phaser 2 is now fully locked - all changes like this are for Phaser 3 only.
Yes, I understand that using require would be a bigger undertaking.
Do you think the hack I did (https://github.com/mkristo/phaser/commit/6d742155bf5fdb93a9593755a3e718344b5b5bfe) would be OK to get into 2.4?
And maybe even the following hack https://github.com/mkristo/phaser/commit/17c07685214baa38393ecb91df6f03b277824d90 to make sure Phaser provides a way to use PIXI internals?
Yes I'd be happy to merge that in.
Thanks! Pull request coming in a bit.
Pull request added here: https://github.com/photonstorm/phaser/pull/1923