Skip to content

Instantly share code, notes, and snippets.

@caasig
Created February 26, 2016 04:45
Show Gist options
  • Save caasig/e585afbef1f964c9bc89 to your computer and use it in GitHub Desktop.
Save caasig/e585afbef1f964c9bc89 to your computer and use it in GitHub Desktop.
/* global module */
/**
* Based on https://github.com/substack/node-browserify/issues/1044#issuecomment-139384663
*/
(function (module) {
module.exports = bundleEntry;
var through2 = require('through2'),
browserify = require('browserify'),
watchify = require('watchify');
var cachedBundles = {};
function bundleEntry(onUpdate, shouldWatch) {
shouldWatch = shouldWatch || false;
var transformation = through2.obj(function (file, enc, next) {
var filename = file.path;
var config = {
entries: [filename],
transform: []
};
function onBundleCB(err, res) {
if (err) {
return next(err);
}
file.contents = res;
next(null, file);
}
// Watchify configs
if (shouldWatch) {
if (cachedBundles[filename]) {
// Already created a watched bundle, just rebundle
return cachedBundles[filename].bundle(onBundleCB);
} else {
config.cache = {};
config.packageCache = {};
config.debug = false;
}
}
var b = browserify(config);
if (shouldWatch) {
b = watchify(b);
cachedBundles[filename] = b;
b.on('update', function () {
console.log(filename + " changed. Rebundling...");
onUpdate(filename);
});
}
b
.on('error', handleError) // No idea if this is needed (just calls this.end)
.bundle(onBundleCB);
});
return transformation;
}
function handleError() {
console.log('Bundle error');
console.log(arguments);
this.emit('end'); // Keep gulp from hanging on this task
}
})(module);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment