Created
August 20, 2021 20:18
-
-
Save kissarat/8acfa4275af13cf52b74ccc9c8ed0fee to your computer and use it in GitHub Desktop.
Webpack plugin to reload UI when something changed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Webpack plugin to reload UI when something changed | |
const http = require('http') | |
const requests = [] | |
function Watch() { | |
this.serve() | |
} | |
Watch.prototype = { | |
serve() { | |
const server = http.createServer(function (req, res) { | |
res.writeHead(200, { | |
'Access-Control-Allow-Origin': '*', | |
'Content-Type': 'text/event-stream', | |
}) | |
if ('GET' === req.method) { | |
requests.push(res) | |
res.write('event: online\ndata: {}\n\n') | |
} | |
else { | |
res.end() | |
} | |
}) | |
server.listen(7001) | |
}, | |
apply(compiler) { | |
compiler.plugin("compile", () => requests.forEach(res => res.write('event: start\ndata: {}\n\n'))) | |
compiler.plugin("done", () => requests.forEach(res => res.write('event: reload\ndata: {}\n\n'))) | |
} | |
} | |
module.exports = Watch |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Browser code for reloading plugin | |
module.exports = function watchClient() { | |
if (+localStorage.getItem('debug')) { | |
const eventSource = new EventSource('http://localhost:7001/') | |
var offline = false | |
function reloading() { | |
document.body.innerHTML = '<div class="webpack reloading">Please Wait...</div>' | |
// setTimeout(() => location.reload(), 20000) | |
} | |
eventSource.addEventListener('start', reloading) | |
eventSource.addEventListener('online', function () { | |
if (offline) { | |
reloading() | |
offline = false | |
} | |
}) | |
eventSource.addEventListener('reload', function () { | |
location.reload() | |
}) | |
eventSource.addEventListener('error', function (e) { | |
offline = true | |
document.body.innerHTML = '<div class="webpack offline">offline</div>' | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment