Using p5.js via npm

Hey there!
I downloaded p5 via npm locally in one of my projects. Now how do I import it to the index.html file?

Is doing this worth it? Or should I rather abandon this idea and use the CDN instead?

  • Let’s say you have a folder named “MySketch”.
  • And inside that folder a file called “sketch.js”:
'use strict';

function setup() {
  createCanvas(800, 600).mousePressed(redraw);
  noLoop();
}

function draw() {
  background('#' + hex(~~random(0x1000), 3));
}
  • Then you open the command shell while inside that folder and type in: npm i -D p5
  • You’ll get a subfolder “node_modules” and 2 files: “package.json” & “package-lock.json”.
  • In order to load both “sketch.js” and the acquired “p5.js” file inside “node_modules/p5/lib/” you’d create an “index.html” template like this:
<script defer src=node_modules/p5/lib/p5.js></script>
<script defer src=sketch.js></script>
  • However you could simply scrap all that and just get it remotely from a CDN:
<script defer src=https://cdn.JsDelivr.net/npm/p5></script>
<script defer src=sketch.js></script>
1 Like

Thank you @GoToLoop.
I have another question: I have my project inside a long path of sub-folders. So is there a way I can lead the path variable staright to the root repository and then into the node modules?

You can use ../ in order to go up to the parent folder of the current folder.

You can also begin from the base folder by starting the path w/ /:

<script defer src=/node_modules/p5/lib/p5.js></script>
1 Like