Phaser with RequireJS and Bower

 

Not sure how much use this will be to anyone, but I thought I would share it all the same…  I recently found myself working with Phaser without the comforts of my friend TypeScript.  One of the great things TypeScript brings to the table is a built in package system, something Javascript is sorely lacking ( at least until ECMAScript 6 arrives ).  Of course, you don’t need a modular package system, but it certainly makes things cleaner, especially as project scope increases.  

 

In the land of module loaders, there are two commonly used front runners.  RequireJS and Browserify.  I believe RequireJS is by far the more popular option, so that’s the route I pursued.  That Phaser already shipped with a RequireJS template was certainly an added bonus!

 

So, let’s take a look at how you use that template.  First you have to get it… I didn’t make the obvious git pun, aren’t you proud?

 

Anyways, as the line above might hint, the template is available in the Phaser Git repository.  That said, pulling the entire repository just to get a single directory is stupidly overkilled.  Unfortunately, it’s all the only option you’ve got with Git.  Sadly there is no ability to download a single folder with git or using the Github web interface.  However, Github is compatible with SVN, and this is one area where SVN shines compared to git.

 

The template we want is in the directory https://github.com/photonstorm/phaser/tree/master/resources/Project%20Templates/RequireJS.  Using SVN ( assuming you have it installed, if you have a Mac with Xcode installed, you should have SVN, if you are on Windows it’s available in cygwin ), you can download just this folder using the command:

 

 

This will download the contents of that folder on github to the local directory ./RequireJS, which it will create.  ( In fact, the command will fail if it already exists ).

 

Now that we have the template, what exactly do we do with it?

 

Well the first thing we need to do is resolve the dependencies.  That is, download all the libraries that it depends on.  This particular template uses the bower package manager.  To be honest, it’s rather overkill, as this package only has two dependencies… requireJS and Phaser, but oh well, it’s always useful to learn and becomes more useful as your project increases in complexity ( kinda like RequireJS actually ), so let’s look at how we use Bower.

 

First you need to install it, and in order to do that, you need to have NodeJS installed.  Node is getting to be the underlying technology for many programming tools, so you should probably have it installed at this point anyways.  To install Node either download and run the installer or use for favourite package manager.  Ironic this, using a package manager to install a package manager to install a different package manager….  Oh, you also need to have git installed.  Again on Mac OS git is installed with Xcode ( or possibly even on it’s own, not certain ) and you can get it on Windows in cygwin or using the installer.

 

Ok, now that you’ve got now installed, you need to install Bower.  To install it globally ( system wide ), simply open a console/terminal window and type

npm install -g bower

 

Now, in your terminal window, change to the directory you installed the template ( ./RequireJS in my case ) and run:

bower install
 
This will read the local file bower.json, and go and download the specified libraries.  This should be the end of it.
 
Unfortunately right now, it isn’t as there is a small bug in the RequireJS template that needs to be fixed first.  Thankfully it’s pretty simple.
 
Open the file /src/main.js and locate the paths section and change it to:
 
        paths: {          	phaser:   'libs/phaser/build/phaser.min'          },  

The key changes are the addition of /build/ to the path and the removal of the extra comma at the end of the line.  Now if you run “bower install”, it will go out and resolve all (two!) of your dependencies… yeah, like I said, kinda overkill at the moment.

 

Let’s take a quick look at the project you are left with:

Proj

 

 

It’s a nice clean expandable layout to build a game around.  The assets folder is where, predictably enough, you put your assets.  src/libs is where bower resolved libraries are download and should generally be safely ignored.  Bower.json is the configuration file that tells Bower what libraries your project depends on, as well as a bit of metadata about your project.  It’s a standard JSON structure that looks like:

 bower.json

{    "name": "Phaser-RequireJS",    "version": "0.1.0",    "description": "Phaser Hello World with RequireJS",      "authors": [      "mike <[email protected]>"    ],      "license": "MIT",      "dependencies": {      "requirejs": "latest",      "phaser": "latest"    },      "ignore": [      "src/libs"    ]  }  

 

Next up is our index.html which is a boot loader of sorts.

index.html

<!doctype html>  <html>      <head>          <meta charset="UTF-8" />          <title>hello phaser-requirejs</title>          <script data-main="src/main" src="src/libs/requirejs/require.js"></script>      </head>      <body>      </body>  </html>  

 

This file is pretty much just kicking off the require.js script.  That parameter data-main is important, as it tells require.js the entry point of our application.  Lets look at it next.

main.js

(function () {      'use strict';        requirejs.config({          baseUrl: "src/",                    paths: {          	phaser:   'libs/phaser/build/phaser.min'          },            shim: {          	'phaser': {          		exports: 'Phaser'          	}          }      });         require(['phaser', 'game'], function (Phaser, Game) {  		var game = new Game();  		game.start();      });  }());  

 

This file is scarier looking, but generally not something you have to touch, except when you add new libraries.  Basically you are calling the config() method of requirejs pathing to the phaser library.  require then makes a closure that creates a new instance of Game and calls game.start().

Now the nice part about using a template… you don’t have to write this ugly code, someones already done it for you!  The only time you need to edit this file is when you add new external dependencies.  

Finally, let’s look at game.js, which is basically the starting point of your new game:

game.js

define([      'phaser'  ], function (Phaser) {      'use strict';        function Game() {          console.log('Making the Game');      }            Game.prototype = {      	constructor: Game,            start: function() {              this.game = new Phaser.Game(800, 600, Phaser.AUTO, '', {                  preload: this.preload,                  create: this.create              });          },            preload: function() {              this.game.load.image('logo', 'assets/phaser.png');          },  		          create: function() {              var logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'logo');              logo.anchor.setTo(0.5, 0.5);          }      };            return Game;  });  

 

This looks pretty much like a standard Phaser application.  The only difference is that again it’s wrapped in a closure with a dependency on Phaser.

 

You can read more about defining modules in Require here.

 

I will admit this seems like massive overkill.  It’s quite possible that it is actually, I’ve yet to decide.  The require module system adds some ugliness to the whole process, all module systems do ( and frankly this is why Typescript’s import system is so nice ).

 

For a small project with few dependencies, this is certainly all overkill.   However, as you add more and more dependencies and your code becomes more and more complex, taking a modular approach to managing complexity pays greater and greater rewards.

 

In the end though, is it worth it?   I’m not entirely sure.  Frankly if I had a complex enough application to justify all of this, I’d just use Typescript personally.

Programming


Scroll to Top