Vite, TypeScript & Shipping
The playgrounds in this course load Three.js from a CDN through an import map. A game you ship needs more: TypeScript and autocompletion while you write it, a dev server that reloads instantly, a production build that bundles and minifies your code, hashed file names so players never get a stale mix of old and new files, and a way to put the result on itch.io or your own site. Vite does all of that with almost no configuration. (The Vite course covers the tool in depth; this lesson is the Three.js-specific part.)
Project setup
npm create vite@latest crystal-meadow -- --template vanilla-ts
cd crystal-meadow
npm install three @dimforge/rapier3d-compat
npm install -D @types/three
npm run dev # http://localhost:5173 with hot reloadA layout that scales from a jam game to a bigger project:
crystal-meadow/
index.html <canvas>, HUD and menu markup, <script type="module" src="/src/main.ts">
public/ copied as-is to the build: decoders, files loaded by URL at runtime
libs/draco/ (copied from node_modules/three/examples/jsm/libs/draco)
libs/basis/
models/level.glb
audio/pickup.ogg
src/
main.ts boot: renderer, loading screen, start the game
game/loop.ts fixed-step loop, input, pause (the "play kit")
game/world.ts level loading, colliders
game/player.ts character controller, camera
game/ui.ts HUD and menus
vite.config.ts
tsconfig.jsonTypeScript catches the kind of mistakes this course warned about at compile time: a misspelled property (mesh.positon), passing a Vector3 where a Quaternion is expected, or using an API that no longer exists in your Three.js version (the @types/three package follows Three.js releases, so keep its version in step: three@0.186.x with @types/three@0.186.x).
Assets: public/ or import
| Put it in | Reference it as | Use for |
|---|---|---|
public/models/level.glb |
'/models/level.glb' (or import.meta.env.BASE_URL + 'models/level.glb') |
large files loaded at runtime, decoder folders, anything with a fixed name |
src/assets/hero.glb |
import heroUrl from './assets/hero.glb?url' or new URL('./assets/hero.glb', import.meta.url).href |
files that should get a hashed name for cache-busting |
import heroUrl from './assets/hero.glb?url'; // becomes e.g. /assets/hero-3f9a1c.glb in the build
const gltf = await loader.loadAsync(heroUrl);Vite only knows about file types it understands by default; for .glb/.gltf/.hdr/.ktx2 imports without ?url, add them to assetsInclude in the config.
The config for a web game
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
base: './', // relative URLs: the build works in any folder (itch.io, GitHub Pages subpaths)
assetsInclude: ['**/*.glb', '**/*.hdr', '**/*.ktx2'],
build: {
target: 'es2022', // top-level await (RAPIER.init()) needs a modern target
sourcemap: true, // readable stack traces from players' bug reports
chunkSizeWarningLimit: 1500, // three + rapier are large; don't panic at the warning
},
});npm run build writes dist/: an index.html, hashed JS chunks and assets. npm run preview serves that build locally; always test the build, not only the dev server, before uploading (paths, base, and decoders in public/ are the usual surprises).
Download size
Players on phones and in other countries download your game over slow connections. Know your numbers:
// Download time for a game's files at different connection speeds (megabits per second).
const files = { 'JS (three + rapier + game, gzip)': 0.9, 'level.glb (meshopt)': 2.5, 'textures (KTX2)': 6, 'audio (ogg)': 1.6 };
const totalMB = Object.values(files).reduce((a, b) => a + b, 0);
console.log(`total download: ${totalMB.toFixed(1)} MB`);
for (const [name, mbps] of [['fast home broadband', 100], ['good 4G', 20], ['slow 4G / busy wifi', 5], ['3G', 1.5]]) {
const seconds = (totalMB * 8) / mbps;
console.log(`${name.padEnd(20)} ${String(mbps).padStart(3)} Mbit/s -> ${seconds.toFixed(1).padStart(5)} s`);
}total download: 11.0 MB
fast home broadband 100 Mbit/s -> 0.9 s
good 4G 20 Mbit/s -> 4.4 s
slow 4G / busy wifi 5 Mbit/s -> 17.6 s
3G 1.5 Mbit/s -> 58.7 s
Half a minute of loading loses most casual players. Ways to cut it:
- Compress assets (meshopt/Draco geometry, KTX2 textures, Ogg/Opus audio): see DRACO, KTX2 & Meshopt.
- Load the first level, stream the rest with dynamic
import()for code andloadAsyncfor assets while the player is already playing. - Import only what you use.
import * as THREE from 'three'is tree-shaken by the bundler, but only partially; addons are separate files and only cost something when imported. - Serve with compression. Hosts like Netlify, Cloudflare Pages and GitHub Pages gzip/brotli JS automatically; itch.io serves files as you upload them.
Shipping to itch.io
itch.io's HTML5 games are a zip of your build with index.html at the top level, played in an iframe on the game page.
npm run buildwithbase: './'(itch serves your game from a sub-path).- Zip the contents of
dist/(not thedistfolder itself). - Create a project, set Kind of project: HTML, upload the zip and tick "This file will be played in the browser".
- Set the viewport size, and enable the fullscreen button option and, for first-person games, whatever the page settings currently offer for pointer lock / mobile friendliness. Options change; check the current upload page and documentation.
Other hosts: GitHub Pages (set base to '/<repo>/' or './'), Netlify / Cloudflare Pages / Vercel (connect the repo, build command npm run build, output dist). Any static host works: a Three.js game is just files.
A pre-release checklist
| Check | Why |
|---|---|
Test npm run preview on a phone on the same network (vite preview --host) |
touch input, performance, pixel ratio |
| Open the game in a private window | first-load path, no cached files, no saved data |
| Throttle the network in DevTools (Slow 4G) | loading screen and progress bar behave |
Watch renderer.info.memory across restarts |
geometries/textures that never get disposed |
| Lose and regain focus, switch tabs | pause works, no huge dt after returning |
| Turn the sound off and on | audio starts after a gesture, volume persists |
| Read the console | zero warnings from Three.js (deprecations become removals) |
Test yourself
Why set base: './' in the Vite config for an itch.io upload?
- It enables TypeScript
- It makes asset URLs relative, so the build works when served from an unknown sub-folder
- It compresses the files
- It is required for WebGL
Where should the DRACO and Basis decoder folders go in a Vite project?
- In
src/, imported as modules - In
public/, so they're copied unchanged and their file names stay fixed - In
node_modulesonly - They're bundled automatically
Which package gives you Three.js TypeScript types, and how should its version relate to three?
three-types, any version@types/three, at the same release number asthree- Types are built into
three @three/types, always latest