Include p5.js in Observable notebook

I have recently come across Observable notebooks and I would like to know how to include the p5.js library in the notebook. I have tried the following but it throws a syntax error.

p5 = require(“https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js”)

function setup() {
createCanvas(800,300);
background(220,220,220);
}

function draw() {
// put drawing code here
}

1 Like

I looked through Observable and found two people making p5js notebooks:

I played around with their code and translated your simple test into this.

This Observable notebooks thing seems neat. I use jupyter notebooks regularly for python, and I’m glad there’s a javascript equivalent for this, need to read more on it later. Thanks for mentioning it.

1 Like

There is a processing kernel in Jupyter and one specifically for JavaScript, too. :smiley:

Here is a template for Observable p5.js notebooks:

Also, Tom MacWright has created a helper function which you can import into a notebook to get started quickly, as well as a template with it already in-place:

These are instance mode sketches,and you need to prefix everything – get ready write sketch.foo sketch.bar sketch.baz sketch.etc

One thing I discovered while writing the first template is that the sketches work well, but you cannot currently include libraries like p5.dom and p5.sound in Observable notebooks. I have an open question about that.

Edit:: Including p5.dom in Observable is quite possible – there is a trick to it, shared by twcw and now included in my template notebook (linked above).

1 Like

if you navigate thru’ p5 CDN by jsDelivr - A free, fast, and reliable Open Source CDN, you’re gonna find those addon libraries here: :books:
p5 CDN by jsDelivr - A free, fast, and reliable Open Source CDN

Thank you @GoToLoop.

I actually know where they are via CDNs – the issue is that the Observable “require()” mechanism cannot correctly load the library.

I believe this is because of the (function (root, factory) style immediately-invoked function expression (IIFE) wrapper… see the link to the discussion thread for more. Any suggestions welcome!

Edit: resolved below.

That CDN points directly to the contents of the whole p5.js project in the NPM repo! :point_up_2:

More specifically, I was merely pointing out that both files “p5.dom.js” & “p5.sound.js” are bundled together inside the p5 NPM repo already! :roll_eyes:

Maybe this GitHub issue got some clues to it. Dunno… :confused:

As it turns out, this is a working Observable method for running require on p5 and then adding p5.dom:

p5 = require('p5').then(async p5 => {
  await require('p5@0.6.1/lib/addons/p5.dom.js');
  return p5;
})