P5.js help with running the compiled js


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="dist/style.css">
    <!-- p5.min.js cdn -->
    <script src="dist/sketch.js"></script>


import * as p5 from "p5/index";
let sketch = (p: p5) => {
  p.setup = () => {
    p.createCanvas(p.width, p.height);
  p.draw = () => {
    p.fill(p.color(200, 45, 6));
    p.ellipse(p.random(0, p.width), p.random(0, p.height), p.random(0, 255));


var sketch = function (p) {
    p.setup = function () {
        p.createCanvas(p.width, p.height);
    p.draw = function () {
        p.fill(p.color(200, 45, 6));
        p.ellipse(p.random(0, p.width), p.random(0, p.height), p.random(0, 255));

I wrote this sketch based on some of the typescript related questions I’ve read but I’m having trouble with actually calling it on the page since the function sketch is looking for a p5 instance, how do I call it on my html page?

When using instance mode we need to instantiate the class p5 w/ keyword new and pass our sketch function as its 1st argument:

how do I use instance mode in typescript without actually importing p5? I’m coding for the front-end and my browser keeps having problems with module imports (I already have p5 linked in my html so I’m confused as to whether I need to use webpack or something similar).

The statement import * as p5 from "p5/index"; isn’t about importing the p5.js library itself but rather its corresponding TS types from the file “index.d.ts”.

It means you can only use whatever is “imported” from it to declare datatypes like you did on this line: let sketch = (p: p5) => {

On the line above you’re just declaring that the parameter p is of datatype p5.

However the moment you have something like new p5(sketch); the name p5 isn’t merely a datatype but also the actual p5 class.

That ends up breaking the intention of import * as p5 from "p5/index"; and confuses the TS compiler!

As a workaround you can make a separate file just to have new p5(sketch); on it.

That’s what I did a long time ago on the TS sketch below: