/
index.js
66 lines (49 loc) · 1.57 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
"use strict";
const wrap = require('browserify-wrap');
const chokidar = require('chokidar');
const WSServer = require('ws').Server;
//this code is serialized and injected client-side
//as it might not be processed by browserify transform, keep it ES5
var connect = function(host, port) {
var sock = new WebSocket('ws://' + host + ':' + port);
sock.onopen = function() {
console.log("Connected to browserify-reload handle");
}
sock.onmessage = function(msg){
if(msg && msg.data == "reload")
document.location = document.location.href;
}
};
module.exports = function(b, opts) {
var deferred = opts.deferred;
var port = 0;
var hostname = opts.host || 'document.location.hostname'
var wss = new WSServer({ port }, function() {
port = this.address().port;
console.log("WS server listening on ", port);
//late plugin registration, it's okay
var prefix = `(${connect})(${hostname}, ${port});`;
b.plugin(wrap, {prefix});
});
function broadcast(payload) {
wss.clients.forEach(function(lnk) {
lnk.send(payload);
});
}
var reload = function() { broadcast("reload"); }
if(opts.xfiles)
opts.xfiles.forEach(function(file_path){
chokidar.watch(file_path).on('change', reload);
});
wss.on('connection', function(ws) {
console.log("CONNECTED");
});
b.on("bundle", function(stream) {
stream.on("end", function() {
if(!deferred) {
console.log("NOW ASKING FOR CLIENT TO RELOAD");
reload();
}
})
});
}