#Browserify
###Prevents polluting the global namespace
Everything declared inside a module is local to the module, by default. If you want something declared in a module to be public, so that other modules can use it, you must export that feature. This is done by assigning it to module.exports
. In a separate file, we can import and use exported features by using require()
function:
//myclass.js==============
var MyClass = function() { ... };
module.exports = MyClass;
//index.js===============
var MyClass = require('myclass');
var foo = new MyClass();
When using browserify, every javascript files now has its dependencies listed explicitly at the top of the file through require
functions.
Browserify let's you declare dependencies like jquery and lodash in package.json
and install them with npm install, just like you would in a node project.
{
"name": "My Project",
"version": "1.0.0",
"description": "Example project",
"main": "index.js",
"dependencies": {
"jquery": "^2.1.4",
"lodash": "^3.10.1"
...
}
}
Because browserify bundles all the js files used in a project into a single file, we only need to include it once in our HTML file:
<!-- index.html -->
<!DOCTYPE html>
<head>...</head>
<body>...</body>
<script src="js/bundle.js">
This makes maintaing the project easier because you don't need to constantly add or remove scripts from your HTML. It also has the bonus effect of increase page load times by reducing the number of requests.