webpackHotDevClient.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. // This alternative WebpackDevServer combines the functionality of:
  9. // https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
  10. // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
  11. // It only supports their simplest configuration (hot updates on same server).
  12. // It makes some opinionated choices on top, like adding a syntax error overlay
  13. // that looks similar to our console output. The error overlay is inspired by:
  14. // https://github.com/glenjamin/webpack-hot-middleware
  15. var stripAnsi = require('strip-ansi');
  16. var url = require('url');
  17. var launchEditorEndpoint = require('./launchEditorEndpoint');
  18. var formatWebpackMessages = require('./formatWebpackMessages');
  19. var ErrorOverlay = require('react-error-overlay');
  20. ErrorOverlay.setEditorHandler(function editorHandler(errorLocation) {
  21. // Keep this sync with errorOverlayMiddleware.js
  22. fetch(
  23. launchEditorEndpoint +
  24. '?fileName=' +
  25. window.encodeURIComponent(errorLocation.fileName) +
  26. '&lineNumber=' +
  27. window.encodeURIComponent(errorLocation.lineNumber || 1) +
  28. '&colNumber=' +
  29. window.encodeURIComponent(errorLocation.colNumber || 1)
  30. );
  31. });
  32. // We need to keep track of if there has been a runtime error.
  33. // Essentially, we cannot guarantee application state was not corrupted by the
  34. // runtime error. To prevent confusing behavior, we forcibly reload the entire
  35. // application. This is handled below when we are notified of a compile (code
  36. // change).
  37. // See https://github.com/facebook/create-react-app/issues/3096
  38. var hadRuntimeError = false;
  39. ErrorOverlay.startReportingRuntimeErrors({
  40. onError: function () {
  41. hadRuntimeError = true;
  42. },
  43. filename: '/static/js/bundle.js',
  44. });
  45. if (module.hot && typeof module.hot.dispose === 'function') {
  46. module.hot.dispose(function () {
  47. // TODO: why do we need this?
  48. ErrorOverlay.stopReportingRuntimeErrors();
  49. });
  50. }
  51. // Connect to WebpackDevServer via a socket.
  52. var connection = new WebSocket(
  53. url.format({
  54. protocol: window.location.protocol === 'https:' ? 'wss' : 'ws',
  55. hostname: process.env.WDS_SOCKET_HOST || window.location.hostname,
  56. port: process.env.WDS_SOCKET_PORT || window.location.port,
  57. // Hardcoded in WebpackDevServer
  58. pathname: process.env.WDS_SOCKET_PATH || '/sockjs-node',
  59. slashes: true,
  60. })
  61. );
  62. // Unlike WebpackDevServer client, we won't try to reconnect
  63. // to avoid spamming the console. Disconnect usually happens
  64. // when developer stops the server.
  65. connection.onclose = function () {
  66. if (typeof console !== 'undefined' && typeof console.info === 'function') {
  67. console.info(
  68. 'The development server has disconnected.\nRefresh the page if necessary.'
  69. );
  70. }
  71. };
  72. // Remember some state related to hot module replacement.
  73. var isFirstCompilation = true;
  74. var mostRecentCompilationHash = null;
  75. var hasCompileErrors = false;
  76. function clearOutdatedErrors() {
  77. // Clean up outdated compile errors, if any.
  78. if (typeof console !== 'undefined' && typeof console.clear === 'function') {
  79. if (hasCompileErrors) {
  80. console.clear();
  81. }
  82. }
  83. }
  84. // Successful compilation.
  85. function handleSuccess() {
  86. clearOutdatedErrors();
  87. var isHotUpdate = !isFirstCompilation;
  88. isFirstCompilation = false;
  89. hasCompileErrors = false;
  90. // Attempt to apply hot updates or reload.
  91. if (isHotUpdate) {
  92. tryApplyUpdates(function onHotUpdateSuccess() {
  93. // Only dismiss it when we're sure it's a hot update.
  94. // Otherwise it would flicker right before the reload.
  95. tryDismissErrorOverlay();
  96. });
  97. }
  98. }
  99. // Compilation with warnings (e.g. ESLint).
  100. function handleWarnings(warnings) {
  101. clearOutdatedErrors();
  102. var isHotUpdate = !isFirstCompilation;
  103. isFirstCompilation = false;
  104. hasCompileErrors = false;
  105. function printWarnings() {
  106. // Print warnings to the console.
  107. var formatted = formatWebpackMessages({
  108. warnings: warnings,
  109. errors: [],
  110. });
  111. if (typeof console !== 'undefined' && typeof console.warn === 'function') {
  112. for (var i = 0; i < formatted.warnings.length; i++) {
  113. if (i === 5) {
  114. console.warn(
  115. 'There were more warnings in other files.\n' +
  116. 'You can find a complete log in the terminal.'
  117. );
  118. break;
  119. }
  120. console.warn(stripAnsi(formatted.warnings[i]));
  121. }
  122. }
  123. }
  124. printWarnings();
  125. // Attempt to apply hot updates or reload.
  126. if (isHotUpdate) {
  127. tryApplyUpdates(function onSuccessfulHotUpdate() {
  128. // Only dismiss it when we're sure it's a hot update.
  129. // Otherwise it would flicker right before the reload.
  130. tryDismissErrorOverlay();
  131. });
  132. }
  133. }
  134. // Compilation with errors (e.g. syntax error or missing modules).
  135. function handleErrors(errors) {
  136. clearOutdatedErrors();
  137. isFirstCompilation = false;
  138. hasCompileErrors = true;
  139. // "Massage" webpack messages.
  140. var formatted = formatWebpackMessages({
  141. errors: errors,
  142. warnings: [],
  143. });
  144. // Only show the first error.
  145. ErrorOverlay.reportBuildError(formatted.errors[0]);
  146. // Also log them to the console.
  147. if (typeof console !== 'undefined' && typeof console.error === 'function') {
  148. for (var i = 0; i < formatted.errors.length; i++) {
  149. console.error(stripAnsi(formatted.errors[i]));
  150. }
  151. }
  152. // Do not attempt to reload now.
  153. // We will reload on next success instead.
  154. }
  155. function tryDismissErrorOverlay() {
  156. if (!hasCompileErrors) {
  157. ErrorOverlay.dismissBuildError();
  158. }
  159. }
  160. // There is a newer version of the code available.
  161. function handleAvailableHash(hash) {
  162. // Update last known compilation hash.
  163. mostRecentCompilationHash = hash;
  164. }
  165. // Handle messages from the server.
  166. connection.onmessage = function (e) {
  167. var message = JSON.parse(e.data);
  168. switch (message.type) {
  169. case 'hash':
  170. handleAvailableHash(message.data);
  171. break;
  172. case 'still-ok':
  173. case 'ok':
  174. handleSuccess();
  175. break;
  176. case 'content-changed':
  177. // Triggered when a file from `contentBase` changed.
  178. window.location.reload();
  179. break;
  180. case 'warnings':
  181. handleWarnings(message.data);
  182. break;
  183. case 'errors':
  184. handleErrors(message.data);
  185. break;
  186. default:
  187. // Do nothing.
  188. }
  189. };
  190. // Is there a newer version of this code available?
  191. function isUpdateAvailable() {
  192. /* globals __webpack_hash__ */
  193. // __webpack_hash__ is the hash of the current compilation.
  194. // It's a global variable injected by webpack.
  195. return mostRecentCompilationHash !== __webpack_hash__;
  196. }
  197. // webpack disallows updates in other states.
  198. function canApplyUpdates() {
  199. return module.hot.status() === 'idle';
  200. }
  201. // Attempt to update code on the fly, fall back to a hard reload.
  202. function tryApplyUpdates(onHotUpdateSuccess) {
  203. if (!module.hot) {
  204. // HotModuleReplacementPlugin is not in webpack configuration.
  205. window.location.reload();
  206. return;
  207. }
  208. if (!isUpdateAvailable() || !canApplyUpdates()) {
  209. return;
  210. }
  211. function handleApplyUpdates(err, updatedModules) {
  212. // NOTE: This var is injected by Webpack's DefinePlugin, and is a boolean instead of string.
  213. const hasReactRefresh = process.env.FAST_REFRESH;
  214. const wantsForcedReload = err || !updatedModules || hadRuntimeError;
  215. // React refresh can handle hot-reloading over errors.
  216. if (!hasReactRefresh && wantsForcedReload) {
  217. window.location.reload();
  218. return;
  219. }
  220. if (typeof onHotUpdateSuccess === 'function') {
  221. // Maybe we want to do something.
  222. onHotUpdateSuccess();
  223. }
  224. if (isUpdateAvailable()) {
  225. // While we were updating, there was a new update! Do it again.
  226. tryApplyUpdates();
  227. }
  228. }
  229. // https://webpack.github.io/docs/hot-module-replacement.html#check
  230. var result = module.hot.check(/* autoApply */ true, handleApplyUpdates);
  231. // // webpack 2 returns a Promise instead of invoking a callback
  232. if (result && result.then) {
  233. result.then(
  234. function (updatedModules) {
  235. handleApplyUpdates(null, updatedModules);
  236. },
  237. function (err) {
  238. handleApplyUpdates(err, null);
  239. }
  240. );
  241. }
  242. }