How to use p5.js with TypeScript and webpack
Tags: p5js, typescript, webpack, javascript
Published: 2022-05-19 03:48:30

This post is about creating a p5.js development using webpack and typescript. (Please install Node.js beforehand and make sure npm is available.)

## Step 1: Install libraries
First, create a project directory and install libraries.

```
mkdir p5-project
cd p5-project
npm init -y
npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader @types/p5
npm i p5
```

Delete `"main":"index.js"` in package.json and add `"private":true`

```json
{
  "name": "p5-project",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/p5": "^1.4.2",
    "ts-loader": "^9.3.0",
    "typescript": "^4.6.4",
    "webpack": "^5.72.1",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.9.0"
  },
  "dependencies": {
    "p5": "^1.4.1"
  }
}
```

According to webpack documentation, this is to prevent an accidental publication of your code.

## Step 2: Create directories and files

Create `src` and `dist` directories, `webpack.config.js`, `tsconfig.json` and `global.d.ts` files under the project directory.

The dist directory contains `index.html`, and the src directory contains `index.ts`.

```
p5-project
  |- package.json
  |- package-lock.json
  |- webpack.config.js
  |- tsconfig.json
  |- /dist
    |- index.html
  |- /src
    |- index.ts
```

Each file should be written with reference to the following.

webpack.config.js
```javascript
const path = require('path');

module.exports = {
    mode: "development",
    entry: './src/index.ts',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
    },
    devServer: {
        static: './dist',
    }
};
```

tsconfig.json
```json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node"
  }
}
```

global.d.ts
```typescript
import module = require('p5');
export = module;
export as namespace p5;
```

index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>P5 Project</title>
</head>
<body>
    <script src="bundle.js"></script>
</body>
</html>
```

index.ts
```typescript
import * as p5 from 'p5';

export const sketch = (p: p5) => {
    p.setup = () => {
        p.createCanvas(400, 400);
    }

    p.draw = () => {
        p.background(220);
        p.ellipse(50,50,80,80);
    }
}

export const myp5 = new p5(sketch, document.body);
```
Using the p5 instance mode to avoid possible conflicts with your own function names or other libraries.

## Step 3: Add npm scripts and try to build

Add `"start": "webpack serve --open"` in package.json and type `npm run start` in a terminal.

```json
{
  "name": "p5-project",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack serve --open" //add
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/p5": "^1.4.2",
    "ts-loader": "^9.3.0",
    "typescript": "^4.6.4",
    "webpack": "^5.72.1",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.9.0"
  },
  "dependencies": {
    "p5": "^1.4.1"
  }
}
```
You can see the circle in the canvas on the browser.
![Circle in the canvas on the browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ew8x1ynani0em7vyo4xm.png)
I hope you find this article helpful!
Happy Creative Coding!


Resource refrences:
- [webpack - Getting Started](https://webpack.js.org/guides/getting-started/)
- [webpack - TypeScript](https://webpack.js.org/guides/typescript/)
- [webpack - DevServer](https://webpack.js.org/configuration/dev-server/)
- [p5.js - reference instance mode](https://p5js.org/reference/#/p5/p5)