diff --git a/lib/index.js b/lib/index.js index 8901aed..13f8363 100644 --- a/lib/index.js +++ b/lib/index.js @@ -135,6 +135,18 @@ class WebpackPluginServe extends EventEmitter { return result; } + // #138. handle emitted events that don't have a listener registered so they can be sent via WebSocket + emit(eventName, ...args) { + const listeners = this.eventNames(); + + if (listeners.includes(eventName)) { + super.emit(eventName, ...args); + } else { + const [data] = args; + super.emit('unhandled', { eventName, data }); + } + } + hook(compiler) { const { done, invalid, watchClose, watchRun } = compiler.hooks; diff --git a/lib/routes.js b/lib/routes.js index d47079c..6d78eda 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -79,7 +79,7 @@ const setupRoutes = function setupRoutes() { socket.invalid = (filePath = '', compiler) => { const context = compiler.context || compiler.options.context || process.cwd(); - const fileName = filePath.replace && filePath.replace(context, '') || filePath; + const fileName = (filePath.replace && filePath.replace(context, '')) || filePath; const { wpsId } = compiler; send(prep({ action: 'invalid', data: { fileName, wpsId } })); @@ -97,6 +97,10 @@ const setupRoutes = function setupRoutes() { }); } + // #138. handle emitted events that don't have a listener registered, and forward the message + // onto the client via the socket + this.on('unhandled', ({ eventName, data }) => send(prep({ action: eventName, data }))); + send(prep({ action: 'connected' })); } }; diff --git a/recipes/watch-static-content.md b/recipes/watch-static-content.md index 78da016..b792ff7 100644 --- a/recipes/watch-static-content.md +++ b/recipes/watch-static-content.md @@ -69,7 +69,9 @@ serve.on('listening', () => { }); ``` -The important change there is `serve.emit('reload')`. We're including some sugar data there so that any listeners know where the event originated. That could be useful in an app that has multiple instruction points calling for reloads. +The important change there is `serve.emit('reload')`. The `reload` event isn't actually handled by the `WebpackPluginServe` instance, but the plugin _does_ forward on unhandled, emitted events to all connected `WebSocket`s. The `reload` event is already handled in the client scripts as part of the `liveReload` option, so we can utilize that `WebSocket` message to reload the page. Alternatively, you might choose to connect your own `WebSocket`, use a different action (such as `static-change`), and add more magic than a plain old `window.location.reload()`. + +We're also including some sugar data there in `{source: 'config' }` so that any listeners know where the event originated. That could be useful in an app that has multiple instruction points calling for reloads. ### 🍰 Dessert