Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Packaging and Publishing

Vite, TypeScript and Project Structure

Set up a real Phaser project with Vite and TypeScript: folder layout, typed scenes and events, a production build and testing game logic.

Up to now the lessons loaded Phaser with a <script> tag. That is perfect for learning and small experiments, but a game you plan to publish deserves a real project: a dev server that reloads when you save, a bundler that produces a small optimized build, source files split into modules, and ideally TypeScript, so that mistakes like this.scoer++ are caught before you run anything.

The tool most Phaser developers use today is Vite, a fast dev server and bundler. This lesson walks through creating a project, a sensible folder layout, a typed scene, and the build for release. The site cannot run npm or a bundler in your browser, so the setup parts are read-only commands and files. The TypeScript ideas that matter most for games (typed events, state types, save data) are shown with runnable examples that use plain TypeScript.

Creating the project

You need Node.js (a current LTS release) installed. In a terminal:

Terminal
npm create vite@latest my-game -- --template vanilla-ts
cd my-game
npm install
npm install phaser
npm run dev

The first command scaffolds a TypeScript project. npm install phaser adds the engine, which ships its own type definitions, so there are no extra @types packages. npm run dev starts the dev server (usually at http://localhost:5173) with hot reload. Phaser also publishes official starter templates for Vite with TypeScript; use one if you want a ready-made scene structure, but the files below are small enough to write yourself.

Folder layout

A layout that scales from a prototype to a full game:

TEXT
my-game/
  index.html
  package.json
  tsconfig.json
  vite.config.ts
  public/
    assets/
      images/   audio/   maps/
  src/
    main.ts              entry: creates the Phaser.Game
    config.ts            game config and constants
    scenes/
      Boot.ts  Preloader.ts  MainMenu.ts  Game.ts  Hud.ts  GameOver.ts
    objects/
      Player.ts  Enemy.ts  Bullet.ts
    systems/
      SaveManager.ts  AudioManager.ts  events.ts
    logic/
      scoring.ts  levelGen.ts     pure functions, no Phaser imports

The idea behind the logic folder deserves attention: code that does not need Phaser (scoring rules, level generation, enemy state decisions, save migration) is plain TypeScript. You can test it quickly with a unit test runner without a browser, which is much easier than testing code tangled with sprites.

The entry files

index.html is a minimal page with a container and one script:

HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <title>My Game</title>
    <style>
      html, body { margin: 0; height: 100%; overflow: hidden; background: #000; touch-action: none; }
    </style>
  </head>
  <body>
    <div id="game"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

src/main.ts imports Phaser and the scenes and creates the game:

TypeScript
import Phaser from 'phaser';
import { Boot } from './scenes/Boot';
import { Preloader } from './scenes/Preloader';
import { Game } from './scenes/Game';

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  parent: 'game',
  width: 960,
  height: 540,
  backgroundColor: '#0f172a',
  physics: { default: 'arcade', arcade: { gravity: { x: 0, y: 900 }, debug: false } },
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },
  scene: [Boot, Preloader, Game]
};

new Phaser.Game(config);

Phaser.Types.Core.GameConfig is the type of the configuration object. Your editor now completes option names and underlines a misspelled one, which is already worth the switch.

A typed scene

TypeScript
import Phaser from 'phaser';

export class Game extends Phaser.Scene {
  private player!: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody;
  private cursors!: Phaser.Types.Input.Keyboard.CursorKeys;
  private score = 0;
  private scoreText!: Phaser.GameObjects.Text;

  constructor() {
    super('Game');
  }

  create(): void {
    this.player = this.physics.add.sprite(100, 300, 'hero');
    this.cursors = this.input.keyboard!.createCursorKeys();
    this.scoreText = this.add.text(16, 16, 'Score: 0', { fontSize: '24px' });
  }

  update(): void {
    this.player.setVelocityX(this.cursors.left.isDown ? -200 : this.cursors.right.isDown ? 200 : 0);
  }
}

Two TypeScript details come up constantly with Phaser:

  • Fields that are assigned in create() rather than in the constructor need the definite assignment mark ! (as in player!:), because TypeScript cannot see that create runs before update.
  • this.input.keyboard can be null when keyboard input is disabled, so you write this.input.keyboard! (or check for null) before calling its methods.

Assets in Vite

Files in public/ are served as they are, under the root URL. A file at public/assets/images/hero.png is loaded in preload() as this.load.image('hero', 'assets/images/hero.png'). Files you import from source code (for example import heroUrl from './hero.png') are fingerprinted and optimized by Vite, which gives you cache busting but more ceremony. Most Phaser projects keep everything in public/ and handle caching through the file names or the host's cache headers.

One setting matters for publishing: when the game will live in a sub-folder (itch.io, GitHub Pages project pages, a CDN path), set a relative base in vite.config.ts so that the script and asset links work from any path:

TypeScript
import { defineConfig } from 'vite';

export default defineConfig({
  base: './',
  build: {
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: { manualChunks: { phaser: ['phaser'] } }
    }
  }
});

Phaser itself is around a megabyte when minified (a few hundred kilobytes after gzip), so Vite warns about chunk size. Splitting it into its own chunk means that a game update does not force players to download the engine again, since their browser has it cached under an unchanged file name.

Building for release

Terminal
npm run build      # outputs the optimized site to dist/
npm run preview    # serves dist/ locally to test the real build

The dist/ folder is plain static files: index.html, a hashed JavaScript bundle and your assets. You can upload it to any static host (the next lesson covers publishing). Always test the preview build, not only the dev server, because bundling can reveal missing assets and wrong paths.

Typed events and state

TypeScript is most valuable where mistakes are silent. Event names are the best example: bus.emit('coin-colected', ...) with a typo throws nothing, and the listener never runs. With a typed event map the compiler checks both the name and the payload. The class below is plain TypeScript, so you can run it here. In a project you would use it as src/systems/events.ts and share one instance across scenes (or wrap Phaser's emitter with the same types).

TypeScript A typed event bus

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The same idea types a state machine. A discriminated union describes exactly the states an enemy can be in and the data each one carries, and a switch over kind is checked for completeness: add a new state and the compiler points to every place that must handle it.

TypeScript Typed states and save data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Testing game logic

With the logic/ folder in place, add Vitest (npm install -D vitest) and write ordinary tests:

TypeScript
import { describe, it, expect } from 'vitest';
import { migrate } from '../src/logic/save';

describe('migrate', () => {
  it('upgrades v1 saves', () => {
    expect(migrate({ version: 1, score: 7 })).toEqual({ version: 2, score: 7, best: 7 });
  });
});

Tests like this run in milliseconds, catch regressions in scoring or save code, and need no browser. For whole-game checks use a headless browser tool (Playwright) that loads the preview build and takes a screenshot or reads state exposed through window in a test build.

Common problems

  • Phaser is not defined. You forgot import Phaser from 'phaser' in that file, or you use the global from a script tag in some files and the import in others. Pick one.
  • Assets 404 after deploy. The base path is wrong; set base: './' or the real sub-path.
  • Huge bundle warnings. Normal for Phaser; split it into its own chunk.
  • Type errors on this.input.keyboard. It can be null; use ! or a guard.
  • Class fields reset oddly. Initialize state in init() or create(), as explained in Scene Architecture.
  • Hot reload keeps stale game instances. With Vite HMR, destroy the old game before creating a new one (game.destroy(true) in an import.meta.hot.dispose handler).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why put code such as scoring rules and save migration in a logic folder with no Phaser imports?

    Pure logic can be tested in milliseconds with a test runner. Code that depends on sprites and scenes needs a browser.
  2. 2. What does the base: './' option in vite.config.ts help with?

    Relative URLs let the build work from itch.io, GitHub Pages sub-paths or any folder on a CDN.
  3. 3. Why is a typed event map useful?

    Event typos are silent at run time. With a map of names to payload types the compiler catches them.
  4. 4. In a TypeScript scene, why do fields assigned in create() often carry a ! mark?

    The definite assignment assertion says the field will be initialized, which silences the 'not initialized' error.

Summary

  • Use Vite for a fast dev server and an optimized static build; install phaser with npm and import it as a module.
  • Keep a clear folder structure: scenes, objects, systems, and a Phaser-free logic folder.
  • Serve assets from public/, set base: './' for sub-folder hosting, and split Phaser into its own chunk.
  • TypeScript catches silent mistakes: typed configs, typed event maps, discriminated unions for states and typed save migrations.
  • Test pure logic with Vitest, and always test the preview build before publishing.

Next: Optimizing and Publishing Your Game