Browserify

With Browserify we can use Node modules directly in the browser. This means that you can build your projects with the power of the npm package manager and the Node module syntax exposed in the previous sections. Then Browserify can take your source code and apply some transformations to be able to run your code in the browser environment.

A very simple module that exposes an object with a method that prints a hello message can be written as a Node module:

// hello.js
module.exports = {
  sayHello: function(name) {
    name = name || 'world';
    console.log('hello', name);
  }
}

This simple piece of code can be loaded from another script as shown next:

// main.js
var hello = require('./hello');
hello.sayHello();        // hello world
hello.sayHello('abiee'); // hello abiee

This code works perfectly with Node. You can run it as follows:

$ node main.js

However this code will not run in the browser because the require function and the module object are not defined. Browserify takes your project entry code and tracks all the dependencies to create a single file with all the scripts concatenated:

$ browserify main.js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = {
  sayHello: function(name) {
    name = name || 'world';
    console.log('hello', name);
  }
}

},{}],2:[function(require,module,exports){
var hello = require('./hello');

hello.sayHello();
hello.sayHello('abiee');

},{"./hello":1}]},{},[2]);
Browserify

Figure 4.1 Bundling with Browserify

Note that our code is still in there; Browserify makes the definition of the missing objects and concatenates all the script in a single file. Figure 4.1 shows a graphical representation of what happens. If you use libraries such as Backbone, then your final script will contain all the Backbone code in the output file.

To tell Browserify that you want to create a file instead of just putting the result in the standard output, use the -o flag:

$ browserify main.js -o app.js

That will create an app.js file with the contents of the hello.js and main.js files.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.9.197