Employee Post

Using Browserify with JavaScript (and Keeping Yourself Sane!)

Working with code in the browser is a challenge. Not only do you need to manage the disparate behaviors of a variety of browsers and navigate the sometimes treacherous waters of JavaScript’s functional programming logic, but managing a wide array of dependencies and large projects can quickly get unwieldy.

Browserify is a solution for allowing Node.js style require() calls for importing libraries and your own code in a simple, easy-to-read fashion.

Outside of the browser, it is pretty simple to include a library or additional file in your code (in most languages). In PHP, just calling require ‘filename.php’ does the trick. No such luck in JavaScript…at least not in the browser. In Node.js, the require() function allows for importing external libraries installed by npm or local files. Browserify aims to bring this same ease of use to the browser.

Browserify works by reading through the files passed into it and connecting them all together into a single compiled (with a bit of extra optional magic that I’ll show you, too!) file that you can then load on your site.

Using Libraries

Just like in Node.js, you can require files installed using npm using Browserify, so if I want to include something like Underscore.js I can do something as simple as.

$ npm install underscore

which installs the Underscore.js library into my project’s node_modules directory.

Then in my script I can add:

var _ = require('underscore');

Which loads the Underscore.js library into the _ variable.

Using Your Files

So far so good right? Well, you can also require your own files! Let’s say I have a function yolo, which adds ‘, YOLO right?’ to the end of any string passed to it. Normally you would include this function in your main JavaScript file:

var yolo = function( a ) {
    return a + ', YOLO right?';
}

Which works just fine, but when we start adding to that function with a monstrosity of logic to properly understand the meaning of the string passed in so that the YOLO can be placed at the ideal location for the greatest impact? It now takes up 90% of our file.

Using Browserify, we can separate functions and objects out into individual files to keep our code organized. Requiring a local file is as simple as:

var yolo = require('./yolo.js');

Then in yolo.js we need to adjust our code to tell Browserify what specifically we want to be passed when the file is required.

module.exports = function(a) {
    return a + ', YOLO right?';
}

That module.exports variable is a special object used by Browserify to know exactly what to return when the file is required. You can set module.exports to be whatever you want, including a function as I showed above or an object or array.

Compiling

So now that we have libraries and local files being required, how do we make it so a browser can properly run your code? There are a few different ways, including the actual Browserify package on npm, but I’m going to go over connecting it into Grunt, as that is what we are already using for a lot of our automation here at WebDevStudios.

The grunt-browserify package lets you connect Browserify into your existing watches and tasks to keep your automation all in one place.

A configuration as simple as:

browserify: {
    dist: {
        files: {
            'bundle.js': 'components/main.js'
        }
    }
 },

…will compile the main.js file and all its requirements into the bundle.js file. Of course, this being Grunt, you can also run additional tasks on it such as Uglify, and setup Grunt’s watch task to automatically compile it whenever the JavaScript is edited.

Transforms

Already Browserify is pretty neat, right? But that’s not all! Using Browserify transforms you can do much more, like compiling ES6 or CoffeeScript, loading the contents of template files into a variable, and generally a ton of cool stuff that frees you up to make great, compartmentalized code!

Here is a list of transforms that will give you an idea of how much power some of these have, and here is a quick example of adding a transform to the Browserify Grunt task (after you’ve installed the transform through npm, of course).

browserify: {
    dist: {
        files: {
            'bundle.js': 'components/main.js'
        },
        options: {
            transform: ['jstify']
        }
    }
}

Try it!

I only just started diving in, but the power and benefit of Browserify are already very apparent. The vast majority of projects I’ve worked on can benefit from cleaner dependency management and breaking segments of code into individual files. It’s very easy to get started with, especially if you already have a Grunt workflow setup, and the integration with npm packages is super slick, so try it!

Comments

Have a comment?

Your email address will not be published. Required fields are marked *

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress