forked from deepak1556/gulp-browserify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (76 loc) · 2.21 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var browserify = require('browserify');
var shim = require('browserify-shim');
var path = require('path');
var util = require('util');
var Readable = require('stream').Readable || require('readable-stream');
const PLUGIN_NAME = 'gulp-browserify';
function arrayStream(items) {
var index = 0;
var readable = new Readable({objectMode: true});
readable._read = function() {
if(index < items.length) {
readable.push(items[index]);
index++;
} else {
readable.push(null);
}
};
return readable;
}
module.exports = function(opts, data) {
if(!opts) opts = {};
if(!data) data = {};
['noParse', 'extensions', 'resolve'].forEach(function(opt) {
if(opts[opt]) {
data[opt] = opts[opt];
delete opts[opt];
}
});
function transform(file, enc, cb) {
var self = this;
if (file.isStream()) {
self.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported'));
return cb();
}
// browserify accepts file path or stream.
if(file.isNull()) {
data.entries = file.path;
}
if(file.isBuffer()) {
data.entries = arrayStream([file.contents]);
}
data.basedir = path.dirname(file.path);
var bundler = browserify(data);
if(opts.shim) {
for(var lib in opts.shim) {
opts.shim[lib].path = path.resolve(opts.shim[lib].path);
}
bundler = shim(bundler, opts.shim);
}
bundler.on('error', function(err) {
self.emit('error', new PluginError(PLUGIN_NAME, err));
cb();
});
['exclude', 'add', 'external', 'transform', 'ignore'].forEach( function(method) {
if (!opts[method]) return;
[].concat(opts[method]).forEach(function (args) {
bundler[method].apply(bundler, [].concat(args));
})
})
self.emit('prebundle', bundler);
var bStream = bundler.bundle(opts, function(err, src) {
if(err) {
self.emit('error', new PluginError(PLUGIN_NAME, err));
} else {
self.emit('postbundle', src);
file.contents = new Buffer(src);
self.push(file);
}
cb();
});
}
return through.obj(transform);
};