Use Browserify and Minifyify to Combine, Minify and Obfuscate Multiple JavaScript Files

Posted by: Seth Lakowske

Published:

When you have multiple JavaScript files in node.js (CommonJS) format, you can combine them to create a single bundle of JavaScript that is faster to download and easy to include on a webpage. The rotating triangles in the background are an example of a single bundle.js I've included in this page.

Install Browserify

To get started, install Browserify. Browserify combine source files and their dependencies into one bundle. It does this by using the require statements in your scripts, so you won't need to worry about managing the build, just include the script at the root of your project, conventionally index.js.

I recommend Watchify also. It automatically runs Browserify when source files change, so there isn't a manual build step before browser refreshes.

If you install Browserify and Watchify globally with the -g switch, you can run them on future projects.

sudo npm install browserify -g
sudo npm install watchify -g

Init the project

Create a project directory and run npm init to create a package.json. This file defines project dependencies.
npm init

Now install dependencies.

npm install browserify-shader --save-dev
npm install glmat-4 --save
npm install minifyify --save-dev   
browserify-shader is a development dependency that allow you to include a shader using node-style require statements. glmat-4 is a matrix library useful for doing 3d math (linear algebra). minifyify will minify or shrink your source code down by replacing variable and function names with shorter versions. This process preserves the functionality of your code while making it nearly impossible to read, so you get some obfuscation too.

Run Watchify

Run Watchify to watch files and compile them into a single JavaScript file that we are naming bundle.js. Here the use of browserify-shader plugin allows the glsl shaders to be require'd into the script. And --debug tells Watchify to create a source map for manageable source viewing/debugging

watchify --debug -t browserify-shader index.js -o bundle.js

Obfuscate the bundle

If you are creating open source, you can stop now. Your bundle is ready to use as is. It can help visitors understand the workings of your page if you leave the JavaScript bundle unobfuscated.

On the other hand, If your software is not open source, you may want to obfuscate your code. Assuming you want to obfuscate your Javascript:

browserify index.js -d -p [minifyify --no-map] > bundle.js
# or use watchify to run browserify on your file when they change
watchify -t browserify-shader -d -p [minifyify --no-map] index.js -o bundle.js

And if you're interested in WebGL, feel free to learn from the WebGL Tutorial too!