WDSSocket.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. /* global __webpack_dev_server_client__ */
  2. const getSocketUrlParts = require('./utils/getSocketUrlParts.js');
  3. const getUrlFromParts = require('./utils/getUrlFromParts');
  4. const getWDSMetadata = require('./utils/getWDSMetadata');
  5. /**
  6. * Initializes a socket server for HMR for webpack-dev-server.
  7. * @param {function(*): void} messageHandler A handler to consume Webpack compilation messages.
  8. * @param {string} [resourceQuery] Webpack's `__resourceQuery` string.
  9. * @returns {void}
  10. */
  11. function initWDSSocket(messageHandler, resourceQuery) {
  12. if (typeof __webpack_dev_server_client__ !== 'undefined') {
  13. let SocketClient = __webpack_dev_server_client__;
  14. if (typeof __webpack_dev_server_client__.default !== 'undefined') {
  15. SocketClient = __webpack_dev_server_client__.default;
  16. }
  17. const wdsMeta = getWDSMetadata(SocketClient);
  18. const urlParts = getSocketUrlParts(resourceQuery, wdsMeta);
  19. const connection = new SocketClient(getUrlFromParts(urlParts, wdsMeta));
  20. connection.onMessage(function onSocketMessage(data) {
  21. const message = JSON.parse(data);
  22. messageHandler(message);
  23. });
  24. }
  25. }
  26. module.exports = { init: initWDSSocket };