forked from tounano/gulp-browatchify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (49 loc) · 1.73 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict';
var browserify = require('browserify'),
watchify = require('watchify'),
_ = require('underscore'),
gutil = require('gulp-util'),
through2 = require('through2');
var cache = {},
bundlers = {};
module.exports = function (opts) {
opts = opts || {};
return through2(
{objectMode: true},
function (file, enc, cb) {
var self = this;
var bundler = getBundler(file, opts);
;(function rebundle() {
if (!cache[file.path]) return setImmediate(function (){ rebundle(); });
bundler.bundle()
.on('error', function (e) {self.emit('error', e); cb(); })
.on('data', function (d) {self.push(d)})
.on('end', function () { delete cache[file.path]; setImmediate(function (){cb();})});
})();
}
);
}
function getBundler(file, opts) {
if (bundlers[file.path]) return bundlers[file.path];
var _opts = _.clone(opts);
var transforms = _opts.transforms;
delete _opts.transforms;
bundlers[file.path] =
logBundler(applyTransforms(createBundler(file, _opts, true), transforms)).on('update', function(){ cache[file.path] = true; });
cache[file.path] = true;
return getBundler(file, opts);
//return logBundler(applyTransforms(createBundler(file, _opts, false), transforms));
}
function createBundler(file, opts, watch) {
return (watch ? watchify(browserify(file.path, _.extend(opts || {}, watchify.args))) : browserify(file.path, opts));
}
function applyTransforms (bundler, transforms) {
transforms = transforms || [];
_.each(transforms, function (t) {
bundler.transform(t);
})
return bundler;
}
function logBundler(bundler) {
return bundler.on('log', function (msg) { gutil.log('Browserify: ', msg)});
}