Introduction to Browserify using Gulp!

Installing

$ npm install --save-dev gulp gulp-util gulp-browserify gulp-rename

This will create a package.json file with these packages and a gulfile.js file

To install other packages, e.g gulp_rename:

$ npm install --save-dev gulp-rename

Use within your js:

var rename = require('gulp-rename');

To install jquery:

$ npm install --save-dev jquery

Use within your js:

var $ = require('jquery');

module.exports = function() {
    $('body').html('hello world');
};

Creating a gulpfile

Sample Gulpfile.js

var gulp - require('gulp');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');

// setup task 'js' to fetch main.js file and run it through browserify

gulp.task('js',function() {
    gulp.src('public/js/main.js')
        .pipe(browserify())
         .pipe(rename('public/js/bundle.js'))
         .pipe(gulp.dest('./'));
});

Running

$ gulp js

Watch files for changes and run task 'js'

...
    gulp.task('watch',function() {
    gulp.watch('public/js/**/*.js',['js');
});

Running

$ gulp watch

To run multiple watch commands you will need gulp-sequence as well

$ npm install --save-dev gulp-watch-sequence 

gulp.task('watch', function() {
  gulp.watch('css/*.css',['css']);
        gulp.watch('js/*.js',['js']);
}); 

Debugging

Debugging bundle.js files is difficult as it's all imported into one file. Use sourcemaps to fix this.

To activate, in your gulpfile.js:

...

.pipe(browserify({debug: true})

...

Compressing

$ npm install --save-dev gulp-uglify

In your gulpfile.js we are going to take bundle.js, uglifying it and save as min.js

var uglify = require('gulp-uglify');

...

gulp.task('compress', function() {
    gulp.src('public/js/bundle.js')
        .pipe(uglify())
        .pipe(rename(public/js/min.js'))
        .pipe(gulp.dest('./'));

});

More info