↳ TypeScript
For better developer experience and type-safety while writing p5-svelte sketches, a Sketch
type is exposed from p5-svelte
:
import type { Sketch } from p5-svelte;
Sketch Usage Example
<script lang="ts">
import P5, { type Sketch } from "p5-svelte";
const sketch: Sketch = (p5) => {
p5.setup = () => {
p5.createCanvas(p5.windowWidth, p5.windowHeight);
};
p5.draw = () => {
p5.ellipse(p5.width / 2, p5.height / 2, p5.width, p5.height);
};
}
</script>
<P5 {sketch} />
Exposed Types
p5
We directly re-export the p5
type so that you can use it in more advanced,
modular use-cases allowing direct access to the p5 instance type without needing to explicitly
install
@types/p5
. This enables a single source of entry to p5.js.
// p5-svelte/types.d.ts
import type p5 from 'p5';
/**
* A p5 instance, re-exported from `@types/p5`.
*/
export type p5 = p5;
Sketch
For reference, here is the typedef under the hood - it's admittedly a simple passthrough to the p5 type defs:
// p5-svelte/types.d.ts
/**
* A closure representing a p5 sketch in [Instance Mode](https://github.com/processing/p5.js/wiki/Global-and-instance-mode).
*
* Within the closure you can set optional `preload()`, `setup()`, and/or `draw()` properties on the given p5 instance.
*/
export type Sketch = (sketch: p5) => void;
Intellisense
Not using TypeScript? No worries - you can leverage your IDE's intellisense with jsdoc type hints:
<script>
import P5 from p5-svelte;
/**
* @type {import(p5-svelte).Sketch}
*/
const sketch = (p5) => {
p5.setup = () => {
p5.createCanvas(400, 400);
};
p5.draw = () => {
p5.background(255, 0, 0);
};
};
</script>
<P5 {sketch} />