Browserify to require NPM Modules


I’ve been playing around p5.js and manage to get the sketches running and rendering on the browser with VS code + Live Server.

I wanted to take advantage of NPM modules with the require, but if I use browserify and switch the sketch.js for the bundle.js in the index.html the sketch doesn’t render anymore.

Does anyone has browserify working with p5.js?

Thanks in advance!

Hi! Welcome to the forum :slight_smile: I do often work with npm/browserify with p5.js. For example

Do you want to be more specific? Can you share your project so we can check?

1 Like

Hi @micuat,

I’ve pushed the test file I was working on, to git here: GitHub - diogorsergio/p5-test
Can you have a look? To see if you can see whats happening? It would be really appreciated.

I was trying to use the require method to load a npm module nice-color-palettes.
So when the p5 skech was working what I did was:

  1. npm init
  2. npm install nice-color-palettes sketch.js is already requiring it.
  3. npm install --global browserify
  4. browserify sketch.js > bundle.js


  1. Change index.html to load bundle.js instead of sketch.js.
    • It loads the npm module sucessfuly, console is logging the array that it returns of colors, but the original sketch fails to load on the page.
  2. Change index.html back to sketch.js
    • Npm module fails sketch.js:1 Uncaught ReferenceError: require is not defined, but now the sketch loads ok.


1 Like

Thanks for the detailed info. Have you already worked with browserify before? The idea is that you add all the dependencies in package.json (this case p5.js - note that the npm module is called “p5”). Bundling the sketch without p5 might work but not the way how it is intended.

I imported your project and made it working here - check package.json and app/sketch.js

The problem is that it seems p5.js as a module does not support global mode (more here). When I copied the instance-mode code from the link it works fine. I’m not sure if there is a way to make global mode here, but generally I would recommend switching to instance mode if you are using npm/browserify because weird things can happen around the namespace.

1 Like

Awesome that worked! Thanks for that! :slight_smile:

1 Like