Browserify

(1) Server side JavaScript

(2) run on command mode

 > npm install <package-name>

(1) NodeJS package manager

  •  require()

var $ = require('jquery');

    $.ajax({
        url:'/myapi',
        method:'GET'
    }).success(functon(data){
        // do somthing ...
    });
var foo = require('package-name');
  •  require() / exports()


var mySum = require('./mySum.js');

var result = mySum(2, 3);

// result => 5
var mySum = function(a, b) {

      return a + b;

  };

module.exports = mySum;
  • main.js
  • mySum.js
  • Module Pattern
<!-- common -->
<script src="~/jquery-1.8.2.min.js"></script>
<script src="~/jquery-ui-1.11.4.min.js"></script>
<script src="~/jquery.easing.min.js"></script>
<script src="~/jquery.equalHeights.js"></script>
<script src="~/jquery.cookie.js"></script>
<script src="~/common.js"></script>
<script src="~/jquery.tabSlideOut.v1.3.js"></script>
<script src="~/SearchCompleteV2.js"></script>
<script src="~/aonline-livechat-global.js"></script>
<script src="~/AdvTrack.js"></script>
<script src="~/GoogleAdwords/ad.js"></script>

<!-- project -->
<script src="~/jquery.masonry.min.js"></script>
<script src="~/jsrender.min.js"></script>
<script src="~/underscore-min.js"></script>
<script src="~/es5-shim.min.js"></script>
<script src="~/success-stories.js"></script>

Advantech-success-stories

Front-end pain point -- Dependency

<scirpt src="js/jquery.js">
<scirpt src="js/jq-plugin1.js">
<scirpt src="js/jq-plugin2.js">
<scirpt src="js/jq-plugin3.js">
<script src="js/myApp.js>"
<script>

$('#myDiv').jqPlugin3();
$('.foo').myApp();

</script>

What if we can use CommonJS in front-end …

var $ = require('jquery');
var jqPlugin3 = require('jq-plugin3');
var myApp = require('./myApp.js');

$('#myDiv').jqPlugin3();
$('.foo').myApp();
  • main.js

<scirpt src="js/main.js">

1. one http request.

2. clear dependency.

var jqPlugin1 = require('jq-plugin1');
var jqPlugin2 = require('jq-plugin2');

var jqPlugin3 = function() {
     jqPlugin1().doSomething();
     jqPlugin2().doSomething();
}

module.exports = jqPlugin3;
  • jq-plugin3.js

Browserify lets you require('modules') in the browser by bundling up all of your dependencies.

> npm install -g browserify
> npm install uniq
var unique = require('uniq');

var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];

console.log(unique(data));
> browserify main.js > bundle.js
<script src="bundle.js"></script>

main.js

Demo

Discussion

1. Organize File Structure.

makes CommonJS incompatible files browserifyable.

2. Shim

create src and pub folder.

  • Well js-file dependency. 
  • Well js-coding experience.
  • Lots of packages in NPM.
  • one huge js-file.
  • compile every time.
  • a little complex for debug.

AMD is another popular
module pattern

so... to be continue...

Browserify

By Jayson Chiang

Browserify

  • 565