Phaser and the migration from JavaScript to TypeScript – Step 3 – TypeScript

As promised, here we are with step 3 of the migration from JavaScript to TypeScript in the building of HTML5 games using Phaser.

In step 1 we installed and set up Node.js.

In step 2 I covered npm and Parcel.

Now it’s time to start coding in TypeScript.

First we have to install TypeScript with npm, with

npm install typescript -g

And now you have TypeScript installed.

What now? Let’s create a TypeScript file called script.ts with this content:

s = 'Hello World';
console.log(s);

Then let’s run it with

tsc script.ts

And you will get errors:

A valid JavaScript file, but it doesn’t work in TypeScript because variables must be declared, this way:

const s = 'Hello World';
console.log(s);

or even better, this way:

const s: string = 'Hello World';
console.log(s);

With type declaration.

Now run again

tsc script.ts

Then

npm script.js

And this time you’ll get a result:

This is because TypeScript created a valid JavaScript file which has been executed by Node.js. Look at the generated JavaScript file:

var s = 'Hello World';
console.log(s);

So, from now on, we can say we will be coding in a “cool” JavaScript, which will be translated in a “ugly” JavaScript and executed.

Time to put all together, let’s create a project as seen in Phaser and the migration from JavaScript to TypeScript – Step 2 – npm and Parcel with

npm init -y

As you should know, a file called package.json is created:

Let’s edit it, adding one line:

{
  "name": "test-ts",
  "version": "1.0.0",
  "description": "",
  "main": "script.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "parceltest": "parcel index.html"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Now let’s create index.html:

<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <div id = "main"></div>
        <script src = "script.ts"></script>
    </body>
</html>

Then change script.ts this way:

const s: string = "Hello World";
document.querySelector("#main").innerHTML = s;

Now if we go to command line and write

npm run test

We’ll run the “test” script inside package.json:

So if you call “parceltest” script…

npm run parceltest

It will run Parcel on index.html files, analyse and convert all TypeScript files and run the server as we saw in previous step:

And if we go to http://localhost:1234/, we’ll see the project running:

Our script.ts has also been changed:

{
  "name": "test-ts",
  "version": "1.0.0",
  "description": "",
  "main": "script.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1",
    "parceltest": "parcel index.html"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^4.3.2"
  }
}

Now let’s intall Phaser:

npm install phaser --save

And now Phaser is installed:

package.json changed again:

{
  "name": "test-ts",
  "version": "1.0.0",
  "description": "",
  "main": "script.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1",
    "parceltest": "parcel index.html"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^4.3.2"
  },
  "dependencies": {
    "phaser": "^3.55.2"
  }
}

Now change the content of index.html just like in previous example, but remember to use ts rather than js:

<!DOCTYPE html>
<html>
    <head>
        <script src="game.ts"></script>
    </head>
</html>

This is game.ts:

import Phaser from 'phaser'
import { GameScene } from "./gameScene";

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  width: 640,
  height: 320,
  scene: GameScene
};

new Phaser.Game(config);

And this is gameScene.ts:

export class GameScene extends Phaser.Scene {
    constructor() {
        super({ key: "GameScene" });
    }

    create() {
        this.add.text(10, 10, "HELLO WORLD");
    }
}

Build the project again with

npm run parceltest

And here is our Phaser project up and running at http://localhost:1234/:

Finally we are able to code a Phaser project with TypeScript, but there is still something to see about the IDE to use and the way to define types, see you next time with the fourth and last part.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers