ErrorOverlayEntry.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* global __react_refresh_error_overlay__, __react_refresh_init_socket__, __resourceQuery */
  2. const errorEventHandlers = require('./utils/errorEventHandlers');
  3. const formatWebpackErrors = require('./utils/formatWebpackErrors');
  4. // Setup error states
  5. let isHotReload = false;
  6. let hasRuntimeErrors = false;
  7. /**
  8. * Try dismissing the compile error overlay.
  9. * This will also reset runtime error records (if any),
  10. * because we have new source to evaluate.
  11. * @returns {void}
  12. */
  13. function tryDismissErrorOverlay() {
  14. __react_refresh_error_overlay__.clearCompileError();
  15. __react_refresh_error_overlay__.clearRuntimeErrors(!hasRuntimeErrors);
  16. hasRuntimeErrors = false;
  17. }
  18. /**
  19. * A function called after a compile success signal is received from Webpack.
  20. * @returns {void}
  21. */
  22. function handleCompileSuccess() {
  23. isHotReload = true;
  24. if (isHotReload) {
  25. tryDismissErrorOverlay();
  26. }
  27. }
  28. /**
  29. * A function called after a compile errored signal is received from Webpack.
  30. * @param {string} errors
  31. * @returns {void}
  32. */
  33. function handleCompileErrors(errors) {
  34. isHotReload = true;
  35. const formattedErrors = formatWebpackErrors(errors);
  36. // Only show the first error
  37. __react_refresh_error_overlay__.showCompileError(formattedErrors[0]);
  38. }
  39. /**
  40. * Handles compilation messages from Webpack.
  41. * Integrates with a compile error overlay.
  42. * @param {*} message A Webpack HMR message sent via WebSockets.
  43. * @returns {void}
  44. */
  45. function compileMessageHandler(message) {
  46. switch (message.type) {
  47. case 'ok':
  48. case 'still-ok':
  49. case 'warnings': {
  50. // TODO: Implement handling for warnings
  51. handleCompileSuccess();
  52. break;
  53. }
  54. case 'errors': {
  55. handleCompileErrors(message.data);
  56. break;
  57. }
  58. default: {
  59. // Do nothing.
  60. }
  61. }
  62. }
  63. // Only register if we're in non-production mode and if window is defined
  64. if (process.env.NODE_ENV !== 'production' && typeof window !== 'undefined') {
  65. // Registers handlers for compile errors
  66. __react_refresh_init_socket__(compileMessageHandler, __resourceQuery);
  67. // Registers handlers for runtime errors
  68. errorEventHandlers.error(function handleError(error) {
  69. hasRuntimeErrors = true;
  70. __react_refresh_error_overlay__.handleRuntimeError(error);
  71. });
  72. errorEventHandlers.unhandledRejection(function handleUnhandledPromiseRejection(error) {
  73. hasRuntimeErrors = true;
  74. __react_refresh_error_overlay__.handleRuntimeError(error);
  75. });
  76. }