Skip to content

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

@nbogie

Description

@nbogie

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
  • 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.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions