Getting Started
Konten ini belum tersedia dalam bahasa Anda.
-
Install the package
Terminal window npm i @capgo/capacitor-live-reloadTerminal window pnpm add @capgo/capacitor-live-reloadTerminal window yarn add @capgo/capacitor-live-reloadTerminal window bun add @capgo/capacitor-live-reload -
Sync with native projects
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
Configure your Vite dev server to work with live reload. You need to:
- Disable the built-in HMR client
- Forward reload events over a dedicated WebSocket endpoint
import { LiveReload } from '@capgo/capacitor-live-reload';
// Configure the dev serverawait LiveReload.configureServer({ url: 'http://localhost:5173', websocketPath: '/capgo-livereload', autoReconnect: true, reconnectInterval: 2000});
// Connect to the dev serverawait LiveReload.connect();
// Listen for reload eventsLiveReload.addListener('reloadEvent', (event) => { console.log('Reload event:', event); if (event.type === 'full-reload') { console.log('Full page reload triggered'); } else if (event.type === 'file-update') { console.log('File updated:', event.file); }});
// Listen for connection status changesLiveReload.addListener('statusChange', (status) => { console.log('Connection status:', status.connected); console.log('Server URL:', status.url);});API Reference
Section titled âAPI ReferenceâconfigureServer(options)
Section titled âconfigureServer(options)âStore remote dev server settings for subsequent connections.
const status = await LiveReload.configureServer({ url: 'http://192.168.1.100:5173', websocketPath: '/capgo-livereload', headers: { 'Authorization': 'Bearer token' }, autoReconnect: true, reconnectInterval: 2000});Parameters:
url(string): Base URL for the dev server (e.g.,http://dev.local:5173)websocketPath(string, optional): WebSocket path override (default:/ws)headers(Record<string, string>, optional): Extra headers for WebSocket connectionautoReconnect(boolean, optional): Auto-reconnect on disconnect (default:true)reconnectInterval(number, optional): Delay between reconnect attempts in ms (default:2000)
Returns: LiveReloadStatus with connection info
connect()
Section titled âconnect()âEstablish a WebSocket connection if one is not already active.
const status = await LiveReload.connect();console.log('Connected:', status.connected);Returns: Current connection status
disconnect()
Section titled âdisconnect()âClose the current WebSocket connection and disable auto reconnect.
await LiveReload.disconnect();getStatus()
Section titled âgetStatus()âGet the current connection status.
const status = await LiveReload.getStatus();console.log('Connected:', status.connected);console.log('URL:', status.url);reload()
Section titled âreload()âManually trigger a full reload of the Capacitor WebView.
await LiveReload.reload();reloadFile(options)
Section titled âreloadFile(options)âReload a single file/module (falls back to full reload if not supported).
await LiveReload.reloadFile({ path: '/src/components/MyComponent.tsx', hash: 'abc123'});addListener(âreloadEventâ, callback)
Section titled âaddListener(âreloadEventâ, callback)âListen to incoming reload events from the server.
const handle = await LiveReload.addListener('reloadEvent', (event) => { switch (event.type) { case 'full-reload': console.log('Full reload requested'); break; case 'file-update': console.log('File updated:', event.file?.path); break; case 'error': console.error('Error:', event.message); break; }});
// Remove listener when doneawait handle.remove();addListener(âstatusChangeâ, callback)
Section titled âaddListener(âstatusChangeâ, callback)âListen to socket status changes.
await LiveReload.addListener('statusChange', (status) => { console.log(status.connected ? 'Connected' : 'Disconnected');});removeAllListeners()
Section titled âremoveAllListeners()âRemove all registered listeners.
await LiveReload.removeAllListeners();Complete Example
Section titled âComplete Exampleâimport { LiveReload } from '@capgo/capacitor-live-reload';
export class DevServer { private connected = false;
async initialize() { // Only enable in development if (process.env.NODE_ENV !== 'development') { return; }
try { // Configure server await LiveReload.configureServer({ url: 'http://192.168.1.100:5173', websocketPath: '/capgo-livereload', autoReconnect: true, reconnectInterval: 3000 });
// Set up listeners before connecting await LiveReload.addListener('reloadEvent', this.handleReloadEvent.bind(this)); await LiveReload.addListener('statusChange', this.handleStatusChange.bind(this));
// Connect await LiveReload.connect(); } catch (error) { console.error('Failed to initialize live reload:', error); } }
private handleReloadEvent(event: any) { console.log('Reload event received:', event.type);
switch (event.type) { case 'full-reload': this.performFullReload(); break; case 'file-update': this.handleFileUpdate(event.file); break; case 'error': console.error('Server error:', event.message); break; case 'connected': console.log('Server connected'); break; case 'disconnected': console.log('Server disconnected'); break; } }
private handleStatusChange(status: any) { this.connected = status.connected; console.log(`Live reload ${status.connected ? 'connected' : 'disconnected'}`); }
private performFullReload() { console.log('Performing full page reload...'); window.location.reload(); }
private handleFileUpdate(file: any) { console.log('File updated:', file?.path); // HMR will handle this automatically in most cases }
async disconnect() { await LiveReload.disconnect(); await LiveReload.removeAllListeners(); this.connected = false; }
isConnected(): boolean { return this.connected; }}Vite Configuration Example
Section titled âVite Configuration ExampleâConfigure your Vite server to work with the live reload plugin:
import { defineConfig } from 'vite';
export default defineConfig({ server: { host: '0.0.0.0', // Allow connections from network port: 5173, hmr: { // Custom WebSocket path for live reload path: '/capgo-livereload', } }});Best Practices
Section titled âBest Practicesâ-
Only use in development
if (import.meta.env.DEV) {await LiveReload.configureServer({url: 'http://localhost:5173',websocketPath: '/capgo-livereload'});await LiveReload.connect();} -
Use your local IP for mobile testing
const devServerUrl = process.env.VITE_DEV_SERVER_URL || 'http://192.168.1.100:5173';await LiveReload.configureServer({ url: devServerUrl }); -
Handle connection errors gracefully
try {await LiveReload.connect();} catch (error) {console.warn('Could not connect to dev server, using production build');} -
Clean up on app exit
window.addEventListener('beforeunload', async () => {await LiveReload.disconnect();}); -
Show connection status in UI
LiveReload.addListener('statusChange', (status) => {// Show indicator in dev buildsupdateDevIndicator(status.connected);});
Platform Notes
Section titled âPlatform Notesâ- Works with iOS 11.0+
- Ensure dev server is accessible from your deviceâs network
- May need to configure firewall to allow connections
Android
Section titled âAndroidâ- Works with Android 5.0 (API 21)+
- Use
adb reversefor localhost connections:Terminal window adb reverse tcp:5173 tcp:5173
- Full support for web platform
- Direct WebSocket connection to Vite dev server
Troubleshooting
Section titled âTroubleshootingâConnection fails:
- Verify dev server is running
- Check that device and computer are on same network
- Ensure firewall allows connections on the port
- Use IP address instead of localhost for mobile devices
Slow reload:
- Check network speed
- Reduce reconnect interval
- Optimize Vite build configuration
WebSocket errors:
- Verify websocketPath matches Vite config
- Check for port conflicts
- Ensure headers are correct if using authentication