Getting Started p5.js in TypeScript
Introduction
p5.js is a JavaScript port of Processing which is one of the most famous and easy to write frameworks for creative coding. Though it is so powerful as-is, we can unleash developer experience such as code completion by using p5.js in TypeScript.
In this post, we will explore a minimum configuration to get started developing a p5 sketch in TypeScript.
Summary
- Install p5 and types by npm
- Use Parcel to compile TS and run a dev web server
Installing packages
First of all, create a default package.json
file and add the following Node packages.
$ npm init -y
$ npm i --save p5
$ npm i --save-dev @types/p5
$ npm i --save-dev parcel
In this post, we use Parcel to get the following benefits without writing much configurations.
- Compiling TypeScript codes
- Building HTML that references the compiled codes
- Hosting a dev web server
- Watching changes in the source codes to trigger re-compile & re-build
Creating the first sketch
Create src/index.html
and src/sketch.ts
files. Examples are as follows.
src/sketch.ts
import p5 from 'p5';
const sketch = (p: p5) => {
p.setup = () => {
p.createCanvas(400, 400);
};
p.draw = () => {
p.background('#3178c6');
};
};
new p5(sketch);
p5.js has “instance mode” which is explained in the reference to avoid adding p5 functions to global scope.
Instead of declaring setup()
or draw()
functions globaly, we can instantiate a new insatance of p5 with a runnable function.
src/index.html
<!DOCTYPE html>
<html>
<head>
<title>Sketch</title>
<meta charset="utf-8">
<script type="module" src="sketch.ts"></script>
</head>
<body>
<main></main>
</body>
</html>
Note that src/index.html
references the .ts
version of the code.
Parcel will compile the TypeScript code and output a HTML that references the compiled JavaScript code.
Also, the script tag has an attribute type="module"
that is required to use ES modules and CommonJS syntax for exports and imports in the referenced script.
This behavior is described in the official doc for migration from V1 to V2.
Running dev server
Add a new property soruce
in the package.json
file.
This indicates the entry point of the page, and Parcel uses this for the target of the commands.
And add a new script in scripts
for short hand to run parcel
command.
{
"source": "src/index.html",
"scripts": {
"dev": "parcel --port 8080"
}
}
With this script, a dev server can be launched by $ npm run dev
on port 8080.
The sketch will be running on localhost:8080
on a web browser.
And also, any changes in the source files will trigger auto re-build and reload of the page.
Conclusion
p5.js and the definition of its types could be installed by npm. And by using Parcel, we could set up TS dev environment with a little configuration.
The code completion with TypeScript is so powerful, and I can not back to pure JS ever.
References
- p5.js
- Parcel