Easy Peasy Setup of a Phaser 3 Project With Ionic
So far I haven’t been able to find an up-to-date guide on how to set up a basic Phaser 3 project using Ionic that would also allow me to build it as a mobile application using Cordova.
This post summarizes several existing guides found on the Internet.
Install Ionic
First we will install Ionic as a global Node.js module:
> npm install -g ionic
Once Ionic is installed, we can create a blank project. When asked about which JavaScript framework to use in our new app, we will choose Angular.
> ionic start my-project blankPick a framework! 😁Please select the JavaScript framework to use for your new app. To bypass this prompt next time, supply a value for the
--type option.? Framework: (Use arrow keys)
❯ Angular | https://angular.io
React | https://reactjs.org
We can now serve the blank project with the following command:
> ionic serve
A window will automatically open in your browser pointing to http://localhost:8100
.
Install Phaser 3
Some guides suggest copying the minified Phaser 3 source code into your assets folder. Instead, we will install it as a regular npm
module as follows:
> npm install phaser
If now we try to reload the page served by Ionic, the following error will appear:
[ng] ERROR in node_modules/phaser/types/phaser.d.ts:7744:54 - error TS2304: Cannot find name 'ActiveXObject'.
This issue can easily be solved by making the following changes in our tsconfig.json
file:
- We will add
"scripthost"
to the"lib"
array. - We willl set
"allowSyntheticDefaultImports"
totrue
.
The resulting tsconfig.json
file might look something like this:
Alas, after reloading, you will see another error!
ReferenceError: global is not defined
You can solve this by adding the following snippet inside the <head>
tag of our index.html
:
Those two changes are enough to load the blank project page with no errors whatsoever. Yay!
A simple Phaser component
We will now modify the home Angular component to initialize a simple, empty Phaser 3 game.
We can start by removing the default content of the home.page.html
and just leaving it like this:
The div with id game
will be the container of our game.
We will use the following code in our home.page.ts
file:
This will result in a simple, blank Phaser component on top of which you can build your game or application.
Building the game into an iOS / Android app
To eventually build and run the game as an Android (or iOS) app, we will use the integrated Cordova plugin from Ionic:
> ionic cordova platform add android
> ionic cordova run android
Good luck!