p5.js icon indicating copy to clipboard operation
p5.js copied to clipboard

[p5.js 2.0 Bug Report]: types: global mode typescript sketches require two separate imports from p5

Open nbogie opened this issue 3 weeks ago • 2 comments

Most appropriate sub-area of p5.js?

  • [ ] Accessibility
  • [ ] Color
  • [ ] Core/Environment/Rendering
  • [ ] Data
  • [ ] DOM
  • [ ] Events
  • [ ] Image
  • [ ] IO
  • [ ] Math
  • [ ] Typography
  • [ ] Utilities
  • [ ] WebGL
  • [ ] Build process
  • [ ] Unit testing
  • [ ] Internationalization
  • [ ] Friendly errors
  • [x] Other (specify if possible)

p5.js version

2.1.1

Web browser and version

any

Operating system

any

Steps to reproduce this

Steps:

  1. make a typescript project with node
  2. install p5 2.1.1 package: npm i -D p5
  3. Add the following snippet to your sketch
  4. run it in browser via dev server
  5. observe runtime error in console: ReferenceError: p5 is not defined

Snippet:

import "p5/global";

window.setup = function setup() {
    createCanvas(200, 200);
    console.log(p5.Vector.random2D());
};

alternative attempt:

If we instead write the following snippet with import p5 from "p5/global", the code will run in the browser, but type-checking fails because it thinks there's no Vector property on p5.

import p5 from "p5/global";

window.setup = async function setup() {
    createCanvas(200, 200);
    console.log(p5.Vector.random2D());
};

current workaround

The problem can be fixed by the user with a separate import:

import "p5/global";
import p5 from "p5";

However, not only does this look weird, TS will also nag the user that the second input isn't used (unless they happen to start code in their sketch that makes use of the p5 variable (such as p5.Vector.fromAngle). As a result I expect they'll remove the second import. Then they'll be confused the next day when they can't write p5.Vector.fromAngle(whatever...)

On discord, @davepagurek guided me to a solution: altering global.d.ts to finish with export default p5.

With that alteration (made locally), we could do a single import import p5 from "p5/global"; which sorted type-checking and runtime availability of the p5 variable.

nbogie avatar Nov 27 '25 12:11 nbogie

Hi @davepagurek , thanks for the help with this!

(As discussed, I'm also happy to provide a tiny PR with your solution, if wanted.)

nbogie avatar Nov 27 '25 12:11 nbogie

Thanks for helping identify this problem @nbogie! I'll assign this to you and you can go ahead with a PR.

davepagurek avatar Nov 27 '25 13:11 davepagurek