forked from kgolid/p5ycho
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hot.js
58 lines (52 loc) · 1.43 KB
/
hot.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
const acorn = require('acorn');
/**
* webpack loader for hot patching top level functions on file change
* inspired by https://github.com/jlongster/monkey-hot-loader
*/
module.exports = function (source) {
if (this.cacheable) {
this.cacheable();
}
const ast = acorn.parse(source);
const names = JSON.stringify(
ast.body
.filter(node => node.type == 'FunctionDeclaration')
.map(node => node.id.name));
const s = `${source};
var hot = module.hot;
if (hot) {
hot.accept(err => console.log('error', err));
var keep = (bindings, evalstr) =>
hot.dispose(function (data) {
data.bindings = bindings;
data.evalstr = evalstr;
});
if (!hot.data) {
var bindings = {}, exports = module.exports;
${names}.forEach(function (name) {
var f = eval(name);
var proxied = new Proxy(f, {
apply: function (f, self, args) {
return (bindings[name] || f).apply(self, args);
}
});
eval(name + " = proxied;");
if (exports[name]) exports[name] = proxied;
});
keep(bindings, str => eval(str));
}
else {
var data = hot.data, bindings = data.bindings;
${names}.forEach(function (name) {
bindings[name] = data.evalstr(
'(' +
eval(name).toString()
.replace(/^function \\w+\\(/,
'function (') +
')');
});
keep(bindings, data.evalstr);
}
}`;
this.callback(null, s);
};