Skip to content

Instantly share code, notes, and snippets.

@kiliman
Last active July 4, 2022 14:21
Show Gist options
  • Save kiliman/91b6c133230afa45e69cbc72ce478141 to your computer and use it in GitHub Desktop.
Save kiliman/91b6c133230afa45e69cbc72ce478141 to your computer and use it in GitHub Desktop.
Remix: only purge require cache on changes instead of every request
// Replachment LiveReload component
// Now calls the `/build/__purge__` endpoint prior to reload
export const LiveReload =
process.env.NODE_ENV !== "development"
? () => null
: function LiveReload({
port = Number(process.env.REMIX_DEV_SERVER_WS_PORT || 8002),
nonce = undefined,
}: {
port?: number;
/**
* @deprecated this property is no longer relevant.
*/
nonce?: string;
}) {
let js = String.raw;
return (
<script
nonce={nonce}
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: js`
(() => {
let protocol = location.protocol === "https:" ? "wss:" : "ws:";
let host = location.hostname;
let socketPath = protocol + "//" + host + ":" + ${String(
port
)} + "/socket";
let ws = new WebSocket(socketPath);
ws.onmessage = (message) => {
let event = JSON.parse(message.data);
if (event.type === "LOG") {
console.log(event.message);
}
if (event.type === 'RELOAD') {
console.log('💿 Reloading window ...')
fetch('/build/__purge__').finally(() => {
window.location.reload()
})
}
};
ws.onerror = (error) => {
console.log("Remix dev asset server web socket error:");
console.error(error);
};
})();
`,
}}
/>
);
};
// Express server.js
// create special route that <LiveReload/> will call
// remove the purge call in default handler
app.use('/build/__purge__', (req, res) => {
console.log('💿 Purging require cache')
purgeRequireCache()
return res.send('ok')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment