Skip to content

Instantly share code, notes, and snippets.

@basti1253
Last active August 29, 2015 14:24
Show Gist options
  • Save basti1253/6fc91df36e8bca165e28 to your computer and use it in GitHub Desktop.
Save basti1253/6fc91df36e8bca165e28 to your computer and use it in GitHub Desktop.
gulp browserify task
// @see https://github.com/gulpjs/gulp/blob/master/docs/recipes/browserify-uglify-sourcemap.md
var browserify = require('browserify'),
watchify = require('watchify'),
combiner = require('stream-combiner2'),
gulp = require('gulp'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
gulpUtil = require('gulp-util'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
bundleCollapser = require('bundle-collapser/plugin'),
_ = require('lodash'),
mergeStream = require('merge-stream'),
handleErrors = require('../util/handleErrors'),
config = require('../config/browserify');
function taskRunner(cfg) {
cfg = _.extend({}, taskRunner.defaults, cfg);
var watch = !! cfg.watch;
cfg = _.omit(cfg, 'watch');
if(watch) {
// Add watchify args and debug (sourcemaps) option
cfg = _.extend({}, watchify.args, {
debug : true,
cache : {},
packageCache : {},
fullPaths : true
}, cfg
);
cfg = _.omit(cfg, ['external', 'require']);
}
var bundler = browserify(cfg),
compile = function() {
gulpUtil.log('Bundling', gulpUtil.colors.green(cfg.outputName) + '...');
var streamPipline = [
bundler.bundle(),
source(cfg.outputName)
],
stream;
if(!watch && cfg.debug) {
[].push.apply(streamPipline, [
buffer(),
sourcemaps.init({
loadMaps: true
}),
uglify(),
sourcemaps.write('.')
]);
}
streamPipline.push(gulp.dest(cfg.dest));
stream = combiner.obj(streamPipline);
stream.on('error', handleErrors);
return stream;
};
if(watch) {
bundler = watchify(bundler);
bundler.on('update', compile);
bundler.on('log', gulpUtil.log);
gulpUtil.log('Watching files required by', gulpUtil.colors.green(cfg.outputName));
} else {
bundler.plugin(bundleCollapser);
if(cfg.require) {
bundler.require(cfg.require);
}
if(cfg.external){
bundler.external(cfg.external);
}
}
return compile();
}
taskRunner.defaults = {
debug : true,
outputName: 'app.min.js',
// list of externally available modules to exclude from the bundle
external: [],
// list of modules to make require-able externally
require: []
};
gulp.task('browserify', function() {
if(_.isArray(config.bundles)) {
return mergeStream.apply(gulp, _.map(config.bundles, taskRunner));
}
return taskRunner(config);
});
module.exports = taskRunner;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment