Quantcast
Channel: npm – SitePoint
Viewing all articles
Browse latest Browse all 30

Getting Started with Browserify

$
0
0

JavaScript implementations have been getting more and more complex as the beautiful beast we call the web evolves each year. Many of us now work with JavaScript modules - independently functioning components that come together to work as a cohesive whole, yet can happily have any component replaced without causing armageddon. Many of us have been using the AMD module pattern and RequireJS to accomplish this neatly.

Last year, Browserify hit the scene and brought on a lot of excitement. As the dust starts to settle, I wanted to write up an overview on what Browserify is, how it works, and a few options for adding it into your workflow.

What is Browserify?

Browserify allows us to use node.js style modules in the browser. We define dependencies and then Browserify bundles it all up into a single neat and tidy JavaScript file. You include your required JavaScript files using require('./yourfancyJSfile.js') statements and can also import publicly available modules from npm. It's also quite simple for Browserify to generate source maps for you so that you can debug each JS file individually, despite the fact it's all joined into one.

Why Import node Modules?

Importing modules is a blessing - rather than visit a range of sites to download libraries for your JavaScript, just include them using require() statements, ensure that the modules have been installed and you're good to go. Commonly used JavaScript libraries like jQuery, Underscore, Backbone and even Angular (as an unofficial distribution) are all available to work with. If you're working on a site that already runs node, you're simplifying things even further with one common way to structure all of your JS. I really like that concept.

What You'll Need

To get started with Browserify, the bare minimum you'll need is:

  • node.js
  • npm - this comes installed with node by default.
  • Browserify - I'll explain how to install this one.
  • A pack of JavaScript modules you're ready to tame!

Getting Started

To get started, you'll need node and npm installed on your computer. Head to the links above if you're looking for guidance on getting these installed. If you're totally stuck, try these instructions on installing Node.js via package manager. You won't need to actually do any node work to use Browserify. We're installing node solely because npm runs off it. Once you've got npm, you can install Browserify using the following command:

[code]
npm install -g browserify
[/code]

What we're doing here is using npm to install Browserify globally on your machine (the -g tells npm to install a module globally).

If you get an error that starts with the following:

[code]
Error: EACCES, mkdir '/usr/local/lib/node_modules/browserify'
[/code]

Then you have a permission issue. You can sudo the command, but I recommend checking out this post instead.

Creating Your First Browserify File

Let's start by creating a Browserified JavaScript file that imports an extremely popular module, Underscore. We'll use Underscore to track down Superman. I've called my JS file main.js, and have placed it in a js folder in my project.

We start by assigning the _ variable to Underscore using Browserify's require() statement in our JavaScript:

[js]
var _ = require('underscore');
[/js]

Next, we'll use the each() and find() functions from Underscore. We'll search through two arrays of names and run a console.log to say whether it sees Superman or not. Highly advanced stuff Lex Luthor could only dream of. Our final JavaScript code will look like this:

[js]
var _ = require('underscore'),
names = ['Bruce Wayne', 'Wally West', 'John Jones', 'Kyle Rayner', 'Arthur Curry', 'Clark Kent'],
otherNames = ['Barry Allen', 'Hal Jordan', 'Kara Kent', 'Diana Prince', 'Ray Palmer', 'Oliver Queen'];

_.each([names, otherNames], function(nameGroup) {
findSuperman(nameGroup);
});

function findSuperman(values) {
_.find(values, function(name) {
if (name === 'Clark Kent') {
console.log('It\'s Superman!');
} else {
console.log('... No superman!');
}
});
}
[/js]

We'll want to ensure that Browserify can find the npm module when it tries to add it to our project. The bare basics of doing so involves opening up your terminal, navigating to the folder which holds your JavaScript project, and then running this command to install Underscore in that folder:

[code]
npm install underscore
[/code]

For those unfamiliar with how node and npm work, this creates a folder called node_modules in your project which holds the code for your Underscore module. The command retrieves the latest version of Underscore from the npm repository at https://registry.npmjs.org/underscore. With that module in our node_modules folder, Browserify can now find it and use it.

Running Browserify for the First Time

When we run Browserify, it'll want to build a new JavaScript file with all of our attached modules. In this case, it'll build a JavaScript file with Underscore inside it. We'll need to decide on a name for this new file, I've gone with findem.js. I run this command from my project's root folder:

[code]
browserify js/main.js -o js/findem.js -d
[/code]

This command reads your main.js file and outputs it into the findem.js file defined by the -o option. I've included the -d option so that it'll generate a source map for us too, this way we can debug main.js and underscore cleanly as separate files.

Using the Browserify Output

From there, it's as simple as including the file on your page like any other JS file:

[html]

[/html]

Importing Your Own JavaScript Files

It's unlikely that all of your application will come from node modules. To include your own JavaScript, you can use the same require() function. The following line of JavaScript will import a JS file called your_module.js into the greatestModuleEver variable:

[js]
greatestModuleEver = require('./your_module.js');
[/js]

To import our JavaScript like this, we just need to structure our JavaScript as a module. To do so, we must define module.exports. One way to do this is shown below.

[js]
module.exports = function(vars) {
// Your code
}
[/js]

Side Note!

If you've got a bunch of JavaScript libraries that aren't in npm and you're looking for an easier way to get these all into Browserify, you can use the Browserify-shim npm module to convert these files for you. We won't be using it in this article but some devs might be keen to give that a go.

Our Example with a Module

To give a simple example of how this works, we'll take out the arrays from the previous superhero search example and replace them with a separate JS module that returns an array of names. The module looks like so:

[js]
module.exports = function() {
return ['Barry Allen', 'Hal Jordan', 'Kara Kent', 'Diana Prince', 'Ray Palmer', 'Oliver Queen', 'Bruce Wayne', 'Wally West', 'John Jones', 'Kyle Rayner', 'Arthur Curry', 'Clark Kent'];
}
[/js]

Next, we'll import that module into our code using names = require('./names.js'):

[js]
var _ = require('underscore'),
names = require('./names.js');

findSuperman(names());

function findSuperman(values) {
_.find(values, function(name) {
if (name === 'Clark Kent') {
console.log('It\'s Superman!');
} else {
console.log('... No superman!');
}
});
}
[/js]

Continue reading %Getting Started with Browserify%


Viewing all articles
Browse latest Browse all 30

Trending Articles