CamKode

Basic Setup Your PIXI.js App with Typescript and Webpack

Avatar of Kosal Ang

Kosal Ang

Thu Mar 16 2023

Basic Setup Your PIXI.js App with Typescript and Webpack

Photo by: Florian van Duyn

Setting up your first PIXI, Typescript and Webpack project can be a little complicated, this tutorial is to remind myself and hopefully help someone else get started.

1. Set up your project environment

First, you'll need to install the required dependencies:

1npm install pixi.js typescript webpack webpack-cli webpack-dev-server ts-loader copy-webpack-plugin html-webpack-plugin terser-webpack-plugin
2

Then, create a tsconfig.json file in the root of your project with the following configuration:

1{
2  "compilerOptions": {
3    "target": "es5",
4    "module": "commonjs",
5    "sourceMap": true,
6    "strict": true,
7    "esModuleInterop": true,
8    "forceConsistentCasingInFileNames": true
9  }
10}
11

Then, create a webpack.config.js file in the root of your project with the following configuration:

1const path = require('path')
2const CopyPlugin = require('copy-webpack-plugin')
3const HtmlWebpackPlugin = require('html-webpack-plugin')
4const TerserPlugin = require('terser-webpack-plugin')
5
6module.exports = (env, argv) => {
7  return {
8    stats: 'minimal', // Keep console output easy to read.
9    entry: './src/index.ts', // Your program entry point
10
11    // Your build destination
12    output: {
13      path: path.resolve(__dirname, 'dist'),
14      filename: 'bundle.js',
15    },
16
17    // Config for your testing server
18    devServer: {
19      compress: true,
20      allowedHosts: 'all', // If you are using WebpackDevServer as your production server, please fix this line!
21      static: false,
22      client: {
23        logging: 'warn',
24        overlay: {
25          errors: true,
26          warnings: false,
27        },
28        progress: true,
29      },
30      port: 1234,
31      host: '0.0.0.0',
32    },
33
34    // Web games are bigger than pages, disable the warnings that our game is too big.
35    performance: { hints: false },
36
37    // Enable sourcemaps while debugging
38    devtool: argv.mode === 'development' ? 'eval-source-map' : undefined,
39
40    // Minify the code when making a final build
41    optimization: {
42      minimize: argv.mode === 'production',
43      minimizer: [
44        new TerserPlugin({
45          terserOptions: {
46            ecma: 6,
47            compress: { drop_console: true },
48            output: { comments: false, beautify: false },
49          },
50        }),
51      ],
52    },
53
54    // Explain webpack how to do Typescript
55    module: {
56      rules: [
57        {
58          test: /\.ts(x)?$/,
59          loader: 'ts-loader',
60          exclude: /node_modules/,
61        },
62      ],
63    },
64    resolve: {
65      extensions: ['.tsx', '.ts', '.js'],
66    },
67
68    plugins: [
69      // Copy our static assets to the final build
70      new CopyPlugin({
71        patterns: [{ from: 'assets/' }],
72      }),
73
74      // Make an index.html from the template
75      new HtmlWebpackPlugin({
76        template: 'index.html',
77        hash: true,
78        minify: false,
79      }),
80    ],
81  }
82}
83

2. Create the game canvas

In your index.html file, add a canvas element with an ID of game-canvas:

1<!DOCTYPE html>
2<html>
3  <head>
4    <meta charset="UTF-8" />
5    <title>My Game</title>
6  </head>
7  <body>
8    <canvas id="game-canvas"></canvas>
9  </body>
10</html>
11

3. Initialize PixiJS

In your src/index.ts file, import PixiJS and create a new application instance:

1import * as PIXI from 'pixi.js'
2
3const app = new PIXI.Application({
4  width: 800,
5  height: 600,
6  backgroundColor: 0x1099bb,
7  view: document.getElementById('game-canvas') as HTMLCanvasElement,
8})
9
10// Add your game logic here
11

4. Add game assets

Load your game assets (images, sounds, etc.) using PixiJS's Loader class:

1PIXI.Assets.load(['flowerTop.png'], () => {
2  // Add your game logic here
3})
4

5. Create the game reels

Use PixiJS's Sprite class to create the game:

1const myTexture = PIXI.Texture.from('flowerTop.png')
2
3const mySprite = new PIXI.Sprite(myTexture)
4mySprite.anchor.set(0.5)
5mySprite.x = app.screen.width / 2
6mySprite.y = app.screen.height / 2
7
8app.stage.addChild(mySprite)
9

6. Add game logic

Finally, add your game logic to rotate the sprite and update the game state (e.g. displaying the rotation sprite):

1app.ticker.add((delta) => {
2  mySprite.rotation += 0.05
3})
4

Full src/index.ts code

1import * as PIXI from 'pixi.js'
2
3const app = new PIXI.Application({
4  width: 800,
5  height: 600,
6  backgroundColor: 0x1099bb,
7  view: document.getElementById('game-canvas') as HTMLCanvasElement,
8})
9
10PIXI.Assets.load(['flowerTop.png'], () => {
11  const myTexture = PIXI.Texture.from('flowerTop.png')
12
13  const mySprite = new PIXI.Sprite(myTexture)
14  mySprite.anchor.set(0.5)
15  mySprite.x = app.screen.width / 2
16  mySprite.y = app.screen.height / 2
17
18  app.stage.addChild(mySprite)
19
20  app.ticker.add((_delta) => {
21    mySprite.rotation += 0.05
22  })
23})
24

This is just a basic example to get you started with creating a game using PixiJS and TypeScript.

Related Posts

How to Merge Enumerations in TypeScript

How to Merge Enumerations in TypeScript

There are scenarios where you might want to merge multiple enums into one, combining their respective values into a single type

How to install Tailwind CSS in Next.js

How to install Tailwind CSS in Next.js

TailwindCSS is a popular CSS framework that can help you create nice user interfaces quickly with pre-made CSS classes.

Basic JWT (JSON Web Tokens) with Node.js and TypeScript

Basic JWT (JSON Web Tokens) with Node.js and TypeScript

Below are the steps to work with jsonwebtoken using TypeScript

© 2024 CamKode. All rights reserved

FacebookTwitterYouTube