-
Notifications
You must be signed in to change notification settings - Fork 1
/
watchify.js
85 lines (63 loc) · 1.75 KB
/
watchify.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
"use strict";
var defaults = require("lodash/object/defaults"),
stripAnsi = require("strip-ansi"),
normalizeOptions = require("./common").normalizeOptions,
Builder = require("./Builder");
module.exports = initialize;
function initialize(browserify, watchify) {
return factory.bind(null,browserify,watchify);
}
function factory(browserify, watchify, configure, options) {
options = normalizeOptions(options);
var debug = options.debug,
eager = options.eager,
bify = configure(browserifyProxy),
wify = watchify(bify),
builder = new Builder(bundle,debug),
rebuild = builder.rebuild,
wait = builder.wait;
wify.on("update",updated);
wify.on("bytes",function(bytes) {
debug("Bundle generated (" + bytes,"bytes)");
});
middleware.wait = builder.wait;
middleware.rebuild = builder.rebuild;
return middleware;
function middleware(req, res, next) {
wait(function(err, buf) {
if (err)
next(decolorize(err));
else
sendJS(res,buf);
});
}
function browserifyProxy(options) {
if (Array.isArray(options))
options = { entries: options };
else if (typeof options !== "object")
options = { entries: [options] };
options = defaults({},options,watchify.args);
return browserify(options);
}
function bundle(callback) {
debug("Browserifying");
wify.bundle(callback);
}
function updated(ids) {
debug("Module changes:",ids.join(", "));
rebuild(eager);
}
}
function decolorize(err) {
var stack = err.stack;
if (stack)
err.stack = stripAnsi(stack);
return err;
}
function sendJS(res, buf) {
res.writeHead(200,{
"Content-Type": "application/javascript",
"Content-Length": buf.length
});
res.end(buf);
}