Immediately invoked expression in browserify

I use browserify in combination with node.js so that I can use require() in my js files.

I have this piece of code in my game.js:

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'snakeGame');

var menuState = require('./menuState.js');
var gameState = require('./gameState.js');

game.state.add('menuState', menuState);
game.state.add('gameState', gameState);
game.state.start('menuState');

If i do a browserify game.js -o bundle.js, this piece of code is wrapped inside of an immediately invoked expression and all the required js files are more or less concatenated to this bundle.js

How can I achieve to use the game variable in all my required js files? Since the bundle.js the var game is in the IIFE scope, I cannot access it. How can I put it outside this scope?

EDIT: i think mike c's solution would have worked too. But i was a bit stupid so i just had to define game globally without var infront, that did the trick...

By attaching it to the window object.

window.game = game;

If you want to access your game object elsewhere, export it:

module.exports = game;

If that gives you cyclic dependencies, you have something to improve in the architecture of your application (In case your architecture is fine and you have cyclic dependencies, you can still ask questions)

From that point:

  • If you want to access the game object from other files also bundled in bundle.js,

    Simply do var game = require('game');

  • If you want to access in other scripts loaded in the same page

    • With require:

      Build with browserify -r ./game.js -o bundle.js

      Access in other scripts with var game = require('./game.js');

      Example

    • With require, give an alias to the module:

      Build with browserify -r ./game.js:game -o bundle.js

      Access in other scripts with var game = require('game');

      Example

    • Without require:

      Build with browserify -s game ./game.js -o bundle.js

      Access in other scripts with window.game

      Example