Set up Kaboom.js with Vite and TypeScript

remarkablemark
2 min readJan 19, 2024

--

Kaboom.js
Kaboom.js

This post goes over how to set up a Kaboom.js game with Vite and TypeScript.

Create Kaboom

Generate a Kaboom.js project with create-kaboom:

npm init kaboom -- mygame

We won’t be developing off this project but we’ll copy some of the assets to our Vite project.

Vite

Scaffold a project with Vite:

npm create vite@latest myvite -- --template vanilla-ts

Delete unused files like:

  • public/vite.svg
  • src/counter.ts
  • src/style.css
  • src/typescript.svg

Update vite.config.mts:

import { defineConfig } from 'vite'

export default defineConfig({
build: {
assetsInlineLimit: 0,
},
esbuild: {
minifySyntax: false,
},
})

Disabling build.assetsInlineLimit ensures assets like images don’t get inlined as base64 URLs.

Disabling esbuild.minifySyntax ensures the Kaboom variables don’t get uglified.

Kaboom

Update index.html:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<!-- initialize the context with the `kaboom()` function -->
<script type="module">
import kaboom from 'kaboom'
kaboom()
</script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

The reason we’re initializing kaboom before main.ts is because we want to load kaboom first and add it to the global namespace.

Update src/vite-env.d.ts:

/// <reference types="vite/client" />

import 'kaboom/global'

declare module '*.png' {
const src: string
export default src
}

By importing kaboom/global, you add the global type definitions to your code editor.

By declaring module '*.png', you can use this syntax:

import bean from '/sprites/bean.png'

Copy sprites/bean.png from your create-kaboom project to your Vite project:

mv mygame/sprites/bean.png myvite/public/sprites/bean.png

Update src/main.ts:

// load assets
loadSprite('bean', '/sprites/bean.png')

// add a character to screen
add([
// list of components
sprite('bean'),
pos(80, 40),
area(),
])

// add a kaboom on mouse click
onClick(() => {
addKaboom(mousePos())
})

// burp on 'b'
onKeyPress('b', burp)

Start your game with:

npm run dev

Build your game with:

npm run build

Resources

--

--