Help extending p5 and dependencies in web dev

Here’s a simple template that makes p5 globally available, but still controls when p5 is instantiated:


index.html:

<script defer src=//cdn.JsDelivr.net/npm/p5></script>
<script type=module src=index.mjs></script>

index.mjs:

import runSketch from './sketch.mjs';
runSketch(); // Invoke this after all the rest is ready!

sketch.mjs:

export default function runSketch() {
  // Make p5.js callbacks globally visible:
  globalThis.preload = preload;
  globalThis.setup = setup;
  globalThis.draw = draw;
  globalThis.windowResized = windowResized;

  globalThis.mocha = 'Hack to block p5.js auto global instantiation.';
  p5.instance || new p5; // Globally instantiate p5.js if it hasn't already.
  globalThis._setupDone = void 0; // Suppress duplicate imported warning.
}

function preload() {
}

function setup() {
}

function draw() {
}

function windowResized() {
}

3 Likes