Angular & Browserify
Disclaimer
I'm a N00B.
The Problem
Concatenate all the things!
Pros:
- simple
Cons:
- Doesn't promote modular code
- Have to manually handle source ordering
- Dependencies are unclear
The solution
Module system
Pros:
- Promotes modular code (You don't say!)
- Keeps source in proper order
- Keeps dependencies clear
Cons:
- Can be complex
Enter
- NPM's require() for the browser
- CommonJS syntax
- Integrates with many NPM modules
- Drop dead simple
- Synchronous
- Can be extended with Transforms
The parts of Browserify
Require
var angular = require('angular');
angular.module('app', [])
Bundling
- Walks through your code creating a dependency tree
- Combines all the modules into one "bundle"
- Adds source maps for easy debugging
Transforms
- Plugins for Browserify
- Perform tasks on each module
- Makes Browserify incredibly versatile
Examples
- Browserfy-shim (use global libs)
- DeAMDify (use AMD modules)
- Aliasify (map common file paths)
- Coffeeify (compile CoffeeScript)
- Partialify (require html as JS strings)
Putting it all together
How does this work with Angular?
Browserify manages classes
Angular Manages instances
Organize your app by feature
app/
--- cats/
|--- index.js
|--- cats-ctrl.js
|--- cats-config.js
|--- cats.html
--- unicorns/
|--- index.js
|--- unicorns-ctrl.js
|--- unicorns-config.js
|--- unicorns.html
|--- unicorns-add/
--- components/
|--- unicorn-directive/
|--- index.js
|--- unicorn-dir.js
|--- unicorn.html
unicorn-conf.js
var angular = require('angular');
module.exports = function( $stateProvider ) {
$stateProvider
.state('unicorns', {
url: '/unicorns',
controller: 'unicornCtrl',
template: require('./unicorns.html') // Using partialify
});
};
index.js
var angular = require('angular');
module.exports = angular.module('unicorns', [
require('../components/unicorn-directive/').name
])
.config( require('./unicorn-conf.js') )
.controller( 'unicornCtrl', require('./unicorn-ctrl') );
app.js
var angular = require('angular');
angular.module('app', [
require('./unicorns').name,
require('./cats').name
])
.config( function( $urlRouterProvider ) {
$urlRouterProvider.otherwise('/');
});
Show me the Code!
Resources
- @bclinkinbeard
- Ben's ng-conf talk
- http://benclinkinbeard.com/
The End
AngularJS and Browserify
By Timothy Krell
AngularJS and Browserify
Using AngularJS with Browserify
- 2,564