Skip to content

Instantly share code, notes, and snippets.

@knubie
Last active August 29, 2015 14:27
Show Gist options
  • Save knubie/3c0dfa3d9aa66b4baa2f to your computer and use it in GitHub Desktop.
Save knubie/3c0dfa3d9aa66b4baa2f to your computer and use it in GitHub Desktop.

#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();

Explicit dependencies

When using browserify, every javascript files now has its dependencies listed explicitly at the top of the file through require functions.

Declare dependencies in package.json

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"
    ...
  }
}

Single request for all javascript

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment