Webpacking the p5 addons

Hi. I’m able to get p5 to render drawings, but I can’t get it to import sound addons. The inpector throughs the error: p5 is not defined (inside p5.sound.js:3112).

My code is as follows:

import p5 from './p5/p5'
import './p5/addons/p5.sound';

const containerElement = document.getElementById('p5-container');

const sketch = (p) => {
    let x = 100;
    let y = 100;
    let mic;

    p.setup = function () {
        p.createCanvas(800, 400);
        mic = new p.AudioIn();
        mic.start();
    };

    p.draw = function () {
        p.background(0);
        p.fill(255);
        p.rect(x, y, 50, 50);
    };
};

new p5(sketch, containerElement);

I believe my import paths are correct. Thanks for the help.

2 Likes

Hi! Welcome to Processing. So just to be clear, your import paths are working, but you have a problem with your sound addons?

Thanks for the reply. Well my p5 import seems to be working because I can draw to the canvas but when I try to use the sound addon I get the error mentioned above. So my addon import probably didn’t work, but the path is pointing to the p5.sound file. Does it matter how the files are structured? I downloaded them from p5 and dropped them in my src file. I thought it could also be related to my webpack bundler or maybe how I’m invoking it on the p argument and not p5, but I’m pretty clueless.

For those wondering, I got it to work by just importing through the index.html instead of index.js.

  • p5js and many other JS libraries aren’t ES6 modules yet.
  • So the safest way to import them is via a <script> tag inside an “.html” file:
  • For our own files and ES6 module compatible libraries we can finally use the keywords import & export:
1 Like

@modestfool Not sure if this helps now as it’s very late, but, I was having a similar issue building p5 scripts that rely on p5.sound using Parcel. Due to the fact that p5 is an implicit global in p5.sound the only way I was able to build with Parcel was as follows,

window.p5 = require('p5') 
require('p5/lib/addons/p5.sound')  

new p5(sketch => {
    sketch.setup = () = > {
        console.log('hi there!')
    }
});

If you only need p5 core then the following works,

import p5 from 'p5' 

new p5(sketch => {
    sketch.setup = () = > {
        console.log('hi there!')
    }
});

Hope this helps you or others!