Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

Phaser with Vite and npm: A Real Project Setup

Set up a professional Phaser project with npm and Vite: folder layout, ES modules, scene files, the dev server, TypeScript option and a production build.

A script tag is perfect for learning, but real games grow to dozens of files: scenes, helpers, level data, images, sounds. At that point you want modules (one file per scene), a dev server that reloads the page when you save, and a build step that produces small, optimized files for publishing. The standard way to get all of that is npm plus Vite.

What runs here. The terminal commands and project files below are read-only: this site cannot run npm, Vite or a dev server. The one runnable example imports Phaser as an ES module from a CDN, which is exactly what import Phaser from 'phaser' does in a Vite project, so you can see the module style working.

What you need

  • Node.js (the current LTS version) and npm, which comes with it. Check with node -v and npm -v.
  • A code editor. Visual Studio Code is popular because it understands Phaser's type definitions and offers autocompletion for every method.
  • A browser with developer tools (Chrome, Edge or Firefox).

Create the project

Phaser's team publishes official starter templates, but it is just as easy to build the project yourself, and doing so shows what every file is for. In a terminal:

Terminal
mkdir my-phaser-game
cd my-phaser-game
npm init -y
npm install phaser
npm install --save-dev vite

npm install phaser adds the framework to dependencies; vite is a development tool, so it goes to devDependencies. Your package.json ends up looking like this (version numbers will match what you installed):

JSON
{
  "name": "my-phaser-game",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "phaser": "^4.2.1"
  },
  "devDependencies": {
    "vite": "^7.0.0"
  }
}

Add the "type": "module" and scripts entries by hand. The three scripts are what you will type all the time:

Command What it does
npm run dev Starts the dev server at http://localhost:5173 with hot reload
npm run build Creates an optimized site in the dist folder
npm run preview Serves the dist folder so you can test the real build

Folder layout

TEXT
my-phaser-game/
  index.html
  package.json
  public/
    assets/
      player.png
      jump.ogg
  src/
    main.js
    scenes/
      BootScene.js
      PlayScene.js

Two folders are special:

  • public/ is copied unchanged into the build. Anything here is available from the site root, so public/assets/player.png is requested as assets/player.png. Put images, sounds and map files here and load them in Phaser by that path.
  • src/ holds your code. Vite bundles it, removes unused parts and minifies it.

The HTML entry point

index.html is tiny, because the code arrives through one module script:

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My Phaser Game</title>
  <style>
    html, body { margin: 0; height: 100%; background: #0b1120; }
    #game { width: 100%; height: 100%; }
  </style>
</head>
<body>
  <div id="game"></div>
  <script type="module" src="/src/main.js"></script>
</body>
</html>

ES modules: one scene per file

In a module project, each scene lives in its own file and exports its class. Another file imports it. This is how src/scenes/PlayScene.js looks:

JavaScript
import Phaser from 'phaser';

export default class PlayScene extends Phaser.Scene {
  constructor() {
    super('PlayScene');          // the scene's key
  }

  preload() {
    this.load.image('player', 'assets/player.png');
  }

  create() {
    this.add.image(400, 225, 'player');
  }
}

And src/main.js is the entry that builds the game from the scenes:

JavaScript
import Phaser from 'phaser';
import BootScene from './scenes/BootScene.js';
import PlayScene from './scenes/PlayScene.js';

new Phaser.Game({
  type: Phaser.AUTO,
  width: 800,
  height: 450,
  parent: 'game',
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },
  physics: { default: 'arcade', arcade: { gravity: { y: 600 } } },
  scene: [BootScene, PlayScene]
});

Notice that nothing is global any more. Phaser is imported where it is needed, and every scene file lists its own dependencies. That makes larger games much easier to read.

See the module style run

The runnable example below uses the same import Phaser from 'phaser' line. Because this page has no bundler, an import map tells the browser where the name phaser lives. Vite does this job for you at build time. The two scene classes sit in one script here only because the preview is a single page; in your project each would be its own file.

ES module style with an import map

The dev server and hot reload

Run npm run dev. Vite starts a server and prints a local address. Open it in the browser. When you save a file, Vite reloads the page within a moment. During development this loop (edit, save, see the change) is what makes game building fast.

Two things to know:

  • Vite serves your files over http://, so loading images and audio from public/ works. This is why a dev server matters; double-clicking index.html does not allow the same requests.
  • Open the same address on your phone using your computer's network address (npm run dev -- --host) to test touch controls on a real device.

Production build

npm run build bundles src/main.js and everything it imports into the dist folder: one HTML file, hashed JavaScript and the contents of public/. Phaser is large (over a megabyte before compression), so game bundles are bigger than ordinary web pages. Servers normally compress files (gzip or Brotli) which roughly cuts the size by two thirds. We return to size, hosting and packaging in the Packaging and Publishing chapter.

A very common fix when the build warns about a large chunk is to put Phaser in its own file, so the browser can cache it separately from your game code. In vite.config.js:

JavaScript
import { defineConfig } from 'vite';

export default defineConfig({
  base: './',          // relative paths: the build works from any folder or sub-URL
  build: {
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: { manualChunks: { phaser: ['phaser'] } }
    }
  }
});

base: './' is the setting that most often rescues a game that works locally but shows a blank page after upload to a sub-folder.

TypeScript (optional)

Phaser ships complete type definitions. To use TypeScript, install it and rename files to .ts:

Terminal
npm install --save-dev typescript
TypeScript
import Phaser from 'phaser';

export default class PlayScene extends Phaser.Scene {
  private player!: Phaser.Physics.Arcade.Sprite;

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

  create(): void {
    this.player = this.physics.add.sprite(100, 100, 'player');
  }
}

The ! tells TypeScript that player will be set in create, not in the constructor. With types, your editor completes every Phaser method and warns about wrong arguments. This course uses plain JavaScript so every example runs in the browser as-is, but everything you learn applies unchanged.

Using a different tool

Vite is not the only choice. Webpack, Parcel, esbuild and Rollup all work, and the official Phaser templates exist for several of them. The concepts are identical: install phaser, import it, bundle for production, serve public files from the site root. If you use a framework such as React, Vue or Svelte for menus around the game, create the Phaser.Game inside a component after it mounts and call game.destroy(true) when the component unmounts.

Common problems

  • Images do not load (404). The file is not under public/, or the path starts with /public/. Use assets/player.png.
  • Cannot find module 'phaser'. Run npm install in the folder that contains package.json.
  • Blank page after deploy. Set base: './' in vite.config.js.
  • Two copies of the game on hot reload. Destroy the old game before creating a new one, or let Vite do a full reload.
  • Huge bundle. Normal for Phaser; compress on the server and split Phaser into its own chunk.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you put images and sounds so that Vite copies them unchanged into the build?

    Files in public/ are served from the site root and copied as-is. dist/ is the output folder created by the build.
  2. 2. What does npm run build do in a Vite project?

    vite build creates the production files in dist. npm run dev is the command that starts the dev server.
  3. 3. Why is Phaser added with npm install phaser instead of --save-dev?

    Phaser is part of the shipped game, so it belongs in dependencies. Vite is a build tool, so it goes in devDependencies.
  4. 4. A game works locally but shows a blank page when uploaded to a sub-folder. Which Vite setting is the usual fix?

    A relative base makes asset URLs relative, so the build works under any path.

Summary

  • Use npm and Vite once your game has more than one file: npm install phaser, npm install --save-dev vite, then npm run dev.
  • public/ holds assets served from the root; src/ holds modules that get bundled.
  • Each scene is a module that exports a class with a key; main.js imports them and builds new Phaser.Game.
  • npm run build produces dist; set base: './' for easy hosting and consider a separate Phaser chunk.
  • TypeScript is optional and gives full autocompletion; the course examples stay in JavaScript.

Next: Scenes and the Scene Lifecycle