super big tree

Introduction to browserify

There’s all this wonderful code on npm, the node.js package manager.

What if we could use that code in the browser?

Hey, we can. Use browserify.

With browserify, we can use some core node modules and many of the thousands of modules on npm in our browser-side code.

We can also write our browser-side javascript in the node.js style by using require.

Install browserify:

npm install -g browserify

We use the -g option to install browserify globally on your machine, allowing you to use it on the command line.

Brief example:

// require the core node events module
var EventEmitter = require('events').EventEmitter;

//create a new event emitter
var emitter = new EventEmitter;

// set up a listener for the event
emitter.on('pizza', function(message){
  console.log(message);
});

// emit an event
emitter.emit('pizza', 'pizza is extremely yummy');

Put the above code in a file named index.js.

Now, to be able to run this code in the browser, enter this command in the terminal:

browserify index.js > bundle.js

The bundle.js file now has your event emitter code along with any dependencies on core node modules and shims to make them work in the browser.

You can include bundle.js in your html now like any other javascript file.

Example:

<!DOCTYPE html>
<html>
<head>
  <title>node / browserify example</title>
</head>
<body>

<script src="./bundle.js"></script>
</body>
</html>

That’s it! Now you can use node modules and require in the browser!

Live reload development environment

If you’re in the middle of writing code, you’ll find running browserify in the terminal to regenerate bundle.js, then refreshing the browser to be time-consuming and annoying.

Enter beefy!

beefy is a command-line tool for automatically generating and serving your browserify bundles as you develop. Each time you save your javascript file beefy will regenerate bundle.js and refresh the browser automatically.

Install beefy:

npm install -g beefy

Now, run this:

beefy index.js:bundle.js --live

The --live option enables the live reload functionality of beefy.

This will by default serve your index.html file at http://localhost:9966. Open Chrome, enter that url, then open the javascript console by using the keyboard shortcut command+option+j.

You’ll see pizza is extremely yummy in the javascript console!

This post is a draft of a chapter inĀ Learn.js: a guidebook for building projects with javascript, which you can pre-order.

  1. kmt7 reblogged this from superbigtree
  2. ivanoats reblogged this from superbigtree
  3. pixel67 reblogged this from superbigtree
  4. superbigtree posted this