Add live reload on changes
This commit is contained in:
@@ -5,6 +5,10 @@ interface Props {
|
||||
}
|
||||
|
||||
const { title, primaryColor = '#2d5016' } = Astro.props;
|
||||
|
||||
const liveReloadEnabled = import.meta.env.PUBLIC_LIVE_RELOAD_WS_ENABLED === 'true';
|
||||
const wsPath = import.meta.env.PUBLIC_LIVE_RELOAD_WS_PATH || '/__live_reload';
|
||||
const wsUrl = import.meta.env.PUBLIC_LIVE_RELOAD_WS_URL || '';
|
||||
---
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
@@ -113,5 +117,38 @@ const { title, primaryColor = '#2d5016' } = Astro.props;
|
||||
<slot name="footer">© {new Date().getFullYear()}</slot>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
{liveReloadEnabled && (
|
||||
<script define:vars={{ wsPath, wsUrl }}>
|
||||
(() => {
|
||||
const configuredUrl = (typeof wsUrl === 'string' ? wsUrl : '').trim();
|
||||
const path = (typeof wsPath === 'string' ? wsPath : '/__live_reload').trim() || '/__live_reload';
|
||||
|
||||
const defaultPort = '3001';
|
||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const host = window.location.hostname;
|
||||
|
||||
const url = configuredUrl || `${proto}//${host}:${defaultPort}${path.startsWith('/') ? '' : '/'}${path}`;
|
||||
|
||||
function connect() {
|
||||
const ws = new WebSocket(url);
|
||||
ws.onmessage = (ev) => {
|
||||
try {
|
||||
const msg = JSON.parse(String(ev.data || ''));
|
||||
if (msg && msg.type === 'reload') window.location.reload();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
ws.onclose = () => setTimeout(connect, 1000);
|
||||
ws.onerror = () => {
|
||||
try { ws.close(); } catch { /* ignore */ }
|
||||
};
|
||||
}
|
||||
|
||||
connect();
|
||||
})();
|
||||
</script>
|
||||
)}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user