lazy-compilation-web.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* global __resourceQuery */
  2. "use strict";
  3. if (typeof EventSource !== "function") {
  4. throw new Error(
  5. "Environment doesn't support lazy compilation (requires EventSource)"
  6. );
  7. }
  8. var urlBase = decodeURIComponent(__resourceQuery.slice(1));
  9. var activeEventSource;
  10. var activeKeys = new Map();
  11. var errorHandlers = new Set();
  12. var updateEventSource = function updateEventSource() {
  13. if (activeEventSource) activeEventSource.close();
  14. if (activeKeys.size) {
  15. activeEventSource = new EventSource(
  16. urlBase + Array.from(activeKeys.keys()).join("@")
  17. );
  18. activeEventSource.onerror = function (event) {
  19. errorHandlers.forEach(function (onError) {
  20. onError(
  21. new Error(
  22. "Problem communicating active modules to the server: " +
  23. event.message +
  24. " " +
  25. event.filename +
  26. ":" +
  27. event.lineno +
  28. ":" +
  29. event.colno +
  30. " " +
  31. event.error
  32. )
  33. );
  34. });
  35. };
  36. } else {
  37. activeEventSource = undefined;
  38. }
  39. };
  40. exports.keepAlive = function (options) {
  41. var data = options.data;
  42. var onError = options.onError;
  43. var active = options.active;
  44. var module = options.module;
  45. errorHandlers.add(onError);
  46. var value = activeKeys.get(data) || 0;
  47. activeKeys.set(data, value + 1);
  48. if (value === 0) {
  49. updateEventSource();
  50. }
  51. if (!active && !module.hot) {
  52. console.log(
  53. "Hot Module Replacement is not enabled. Waiting for process restart..."
  54. );
  55. }
  56. return function () {
  57. errorHandlers.delete(onError);
  58. setTimeout(function () {
  59. var value = activeKeys.get(data);
  60. if (value === 1) {
  61. activeKeys.delete(data);
  62. updateEventSource();
  63. } else {
  64. activeKeys.set(data, value - 1);
  65. }
  66. }, 1000);
  67. };
  68. };