Phaser and the migration from JavaScript to TypeScript – Step 2 – npm and Parcel

With Phaser4 version to be released hopefully not that late, it’s recommended to start coding in TypeScript, but before even thinking about TypeScript, in previous post we saw how to install Node.js and npm, then how to start a local server to serve a Phaser game.

Now it’s time to start using npm and Parcel to download Phaser and build a game on the fly, from command line. Still nothing about TypeScript today, but a lot of new stuff to see.

Let’s create a Phaser project with npm.

Create an empty folder, open your shell and write:

npm init -y

A new project will be created, prompting something like this:

As the output says, a new file called package.json has been created in your folder, and its content is:

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

Now let’s install Phaser directly from the official source repository, with

 npm install phaser --save

No more files to manually download, npm will manage everything for you, and after a few seconds you should have Phaser intalled in your project:

Content of package.json also changed, this way:

{
  "name": "phasertest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "phaser": "^3.54.0"
  }
}

Where did npm install Phaser? Somewhere inside node_modules folder. Actually, it’s not important where Phaser has been installed, because npm will handle everything for us.

How did npm know the latest Phaser version is 3.54 (at the time of writing)?

It does not matter, but by installing Phaser this way we’ll always get the latest version.

Now let’s install Parcel, the tool we are using to bundle and create distributable versions of our project, with

 npm install parcel-bundler -g

Another few seconds to wait, then you’ll have Parcel installed:

In some cases, you may get a lot of errors, and have Parcel failing to install: it’s probably because you don’t have Python installed on your computer.

In this case simply go to https://www.python.org/downloads/ and download the latest version:

Then try to install Parcel again and everything should work.

Finally we can start creating our game. Create a folder called game, with three files in it: index.html, game.js and gameScene.js.

This is the content of index.html:

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

I am sure you noticed I am not calling Phaser.

Look at game.js:

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

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

new Phaser.Game(config);

It’s just a basic Phaser game initialization, and the “game” itself comes in GameScene Scene which is declared in gameScene.js:

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

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

What a nice Hello World script! Now how do we run it? We didn’t even linked Phaser in any way.

Let’s start the game from the shell:

parcel ./game/index.html

After a few seconds, a web server is created and Phaser game is launched:

Open http://localhost:1234 on your browser, and here is the game.

Change gameScene.js this way:

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

    create() {
        this.add.text(10, 10, "HELLO WORLD, WHAT A WONDERFUL WORLD!");
    }
}

Just save it, don’t do anything else and look at the web page at http://localhost:1234:

When you update a file, the page is refreshed with your latest changes. How convenient!

Now the point is: where is my Phaser project? It’s in dist folder, look:

Parcel built a bundle with our JavaScript files, added Phaser and here is the final project. The names of your files may change, but this is the concept.

We are talking about 7MB for the JavaScript and more than 10MB for a map file which we do not even need to distribute the project.

When we want to distribute the project, we have to run another command, let’s say we want to save the output in a folder called finalfolder:

parcel build ./game/index.html --no-source-maps --out-dir finalfolder

And this is the output:

Inside finalfolder we’ll find our project ready to be distributed. 1MB of JavaScript file, which is fair, considered there’s both Phaser and the game in it.

And we built and packed a Phaser project using npm and Parcel. Next step, later this week, finally… TYPESCRIPT! Stay tuned.

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