Created
August 1, 2024 03:15
-
-
Save sibelius/07ece8941c6f15649128a7c2a2182a82 to your computer and use it in GitHub Desktop.
ReloadServerPlugin.js
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
const cluster = require('cluster'); | |
const path = require('path'); | |
const defaultOptions = { | |
script: 'server.js', | |
execArgv: [], | |
}; | |
class ReloadServerPlugin { | |
constructor({ script, execArgv = [] } = defaultOptions) { | |
this.done = null; | |
this.workers = []; | |
this.hotReloadSucceeded = false; | |
this.initialCompilationDone = false; | |
cluster.setupPrimary({ | |
exec: path.resolve(process.cwd(), script), | |
execArgv, | |
}); | |
cluster.on('online', (worker) => { | |
this.workers.push(worker); | |
if (this.done) { | |
this.done(); | |
} | |
}); | |
} | |
startServer() { | |
const envs = { | |
NODE_OPTIONS: '--enable-source-maps --no-experimental-fetch --trace-warnings --trace-deprecation', | |
}; | |
cluster.fork(envs); | |
} | |
apply(compiler) { | |
compiler.hooks.afterEmit.tap( | |
{ | |
name: 'reload-server', | |
}, | |
(compilation, callback) => { | |
this.done = callback; | |
// this does not work | |
if (compilation.errors.length === 0) { | |
this.hotReloadSucceeded = true; | |
} else { | |
this.hotReloadSucceeded = false; | |
} | |
const shouldReload = !this.initialCompilationDone || !this.hotReloadSucceeded; | |
if (!this.initialCompilationDone) { | |
this.initialCompilationDone = true; | |
} | |
if (!shouldReload) { | |
return; | |
} | |
this.workers.forEach((worker) => { | |
try { | |
process.kill(worker.process.pid, 'SIGTERM'); | |
} catch (e) { | |
// eslint-disable-next-line | |
console.warn(`Unable to kill process #${worker.process.pid}`); | |
} | |
}); | |
this.workers = []; | |
this.startServer(); | |
}, | |
); | |
compiler.hooks.done.tap('reload-server', (stats) => { | |
if (this.hotReloadSucceeded) { | |
// eslint-disable-next-line | |
console.log('Hot reload succeeded, server not restarted.'); | |
} else { | |
// eslint-disable-next-line | |
console.log('Hot reload failed, server restarted.'); | |
} | |
}); | |
} | |
} | |
module.exports = ReloadServerPlugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment