Talking about HTML5, Javascript, Phaser and TypeScript.
Welcome to step 3 of the series about Phaser, TypeScript and webpack.
In first step we saw how to configure webpack and some plugins to let you develop with Phaser.
In second step we learned how to create distributable versions of the game, but everything was made using JavaScript.
So it’s time to install TypeScript, typing in our console the command to install the TypeScript compiler:
npm install --save-dev typescript
and the command to install the loader:
npm install --save-dev ts-loader
At this time package.json should look like this:
{
"name": "phaserwebpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"development": "webpack serve --open --config webpack.development.js",
"distribution": "webpack --config webpack.distribution.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"phaser": "^3.55.2"
},
"devDependencies": {
"clean-webpack-plugin": "^4.0.0-alpha.0",
"copy-webpack-plugin": "^9.0.1",
"ts-loader": "^9.2.5",
"typescript": "^4.3.5",
"webpack": "^5.48.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
}
}
We also need to create a TypeScript configuration file, with:
tsc --init
This will create a file called tsconfig.json
, with a lot of commented lines, but we can remove them all except for strictPropertyInitialization
which should be set to false
to prevent the compiler to check that each instance property of a class gets initialized in the constructor body, or by a property initializer.
Your tsconfig.json
should look like this, I highlighted the uncommented lines:
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
"strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
Remember to edit line 33 as shown.
When we start working with TypeScript, we need to add some lines to webpack.development.js
and webpack.distribution.js
in order to resolve the new .ts
and .tsx
extensions and tell which loader has to handle these file types.
This is the new content of webpack.development.js
:
const path = require('path');
module.exports = {
entry: {
// this is our entry point, the main TypeScript file
app: './src/main.ts',
},
output: {
// this is our output file, the one which bundles all libraries
filename: 'main.js',
// and this is the path of the output bundle, "dist" folder
path: path.resolve(__dirname, 'dist'),
},
// we are in development mode
mode: 'development',
// we need a source map
devtool: 'inline-source-map',
// development server root is "src" folder
devServer: {
contentBase: './src'
},
// list of extensions to resolve, in resolve order
resolve: {
extensions: [ '.ts', '.tsx', '.js' ]
},
// loader to handle TypeScript file type
module: {
rules: [{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}]
}
}
And this is the new content of webpack.distribution.js
, changing the same lines:
const path = require('path');
// here we use the plugins to clear folders and copy folder content
const CopyPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: {
// this is our entry point, the main TypeScript file
app: './src/main.ts',
},
output: {
// this is our output file, the one which bundles all libraries
filename: 'main.js',
// and this is the path of the output bundle, "dist" folder
path: path.resolve(__dirname, 'dist'),
},
// we are in production mode
mode: 'production',
plugins: [
// here we clean the destination folder
new CleanWebpackPlugin({
cleanStaleWebpackAssets: false
}),
// here we copy some files to destination folder.
// which files?
new CopyPlugin({
patterns: [
{
// src/index.html
from: 'index.html',
context: 'src/'
},
{
// every file inside src/assets folder
from: 'assets/*',
context: 'src/'
}
]
})
],
// list of extensions to resolve, in resolve order
resolve: {
extensions: [ '.ts', '.tsx', '.js' ]
},
// loader to handle TypeScript file type
module: {
rules: [{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}]
}
};
Finally we are ready to convert src/main.js
in src/main.ts
, porting the example to TypeScript:
import 'phaser';
class PlayGame extends Phaser.Scene {
image: Phaser.GameObjects.Image;
constructor() {
super("PlayGame");
}
preload(): void {
this.load.image('logo', 'assets/phaser3-logo.png');
}
create(): void {
this.image = this.add.image(400, 300, 'logo');
}
update(): void {
this.image.rotation += 0.01;
}
}
let configObject: Phaser.Types.Core.GameConfig = {
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
parent: 'thegame',
width: 800,
height: 600
},
scene: PlayGame
};
new Phaser.Game(configObject);
Now, just like in step 2, you can start your development server with:
npm run development
and create your distributable game with
npm run distribution
And now you are ready to start building HTML5 games using Phaser, webpack and TypeScript.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.