-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
66 lines (52 loc) · 1.61 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
var JS_RE = /\.js$/,
browserify = require('browserify'),
thunkify = require('thunkify'),
uglify = require('uglify-js'),
resolve = require('path').resolve;
module.exports = function (options) {
options = options || {};
if ('string' === typeof options) {
options = {root: options};
}
var root = resolve(options.root || '.'),
isProduction = 'production' in options ? options.production : (process.env.NODE_ENV === 'production'),
bundleOpts = {
debug: (!isProduction && options.debug) || false
},
hash = {};
return function* (next) {
var url = this.originalUrl,
minify, code;
if (!JS_RE.test(url)) {
return yield next;
}
if (isProduction && hash[url]) {
return this.body = hash[url];
}
this.type = 'text/javascript';
var fileName = root + url,
b = browserify();
b.add(fileName);
if (options.runtime) {
[].concat(options.runtime).forEach(function (file) {
b.add(file);
});
}
if (options.transform) {
b.transform(options.transform);
}
if (!isProduction) {
return this.body = b.bundle(bundleOpts);
}
try {
code = yield thunkify(b.bundle.bind(b, bundleOpts))();
minify = uglify.minify(code, {fromString: true});
code = minify.code;
} catch (e) {
this.status= 500;
this.body = 'console.error(' + e.stack + ');';
}
hash[url] = code;
this.body = code;
};
};