Idiot Note: Browserify

Learning web development in a time where Javascript is already maturely developed by early developers is surely a good thing. I'm talking about how easy, for example, Express.js has enabled us to make a web application in a very fast and easy way possible.

Despite the conveniences that these kinds of frameworks and packages have, it's easy to overlook the smaller components that make up for those conveniences. And when the time comes when one of those small components need tempering with, it would probably be harder to understand within the context of the framework or the package.

So, that's why it's useful to have at least a minimum knowledge about these "building block" packages. There are a lot of popular such packages that are used. Here, we will look at one of them, which is browserify.

What is it for?

Browserify is used for enabling the usage of CommonJS-style modules in client-side codes. In my last post, I emphasized the importance of modules in server-side Javascript development. Browserify wants to bring the same modular system to client-side development (classic client-side Javascript development only use global variables and functions, no modules involved). 

Why use it?

The main reason you might want to use browserify is because of the abundance of great packages in npm. Suppose you need a library to get a unique member of arrays, and you find array-uniq in npm. Traditionally, you can't use that package in client-side code. But you can with browserify!

How to use it?

  1. Install browserify globally on your computer.
    npm install -g browserify​
  2. Install the package that you want to use (in this example, array-uniq) in your project.
    npm install array-uniq​
  3. Create a file named index.js where you use the array-uniq package.
    // index.js
    const arrayUniq = require('array-uniq');
    a = arrayUniq([1, 1, 2, 3, 3]); // a = [1,2,3]
     
    document.getElementById('my-array').innerHTML = a;​
  4. Run browserify command in terminal. This command will read the code in index.js and translate it into browser-friendly code in a new file named bundle.js.
    browserify index.js > bundle.js​
  5. Test it by creating a file named index.html and include bundle.js in the script. This example will print the unique array into the screen.
    <!DOCTYPE html>
    <html>
        <head>
            <title>Example</title>
        </head>
        <body>
            Array: <span id="my-array"></span>
     
            <!-- include bundle.js here -->
            <script src="bundle.js"></script>
        </body>
    </html>​
  6. Open index.html in the browser and the result should look like this:
  1. You're done! Now, you can use any npm package in your client-side code.

P.S.

There's so much more to learn about browserify. If you're interested here are some useful resources: