Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

275 rindas
7.8 KiB

  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 SockJS = require('sockjs-client');
  16. var stripAnsi = require('strip-ansi');
  17. var url = require('url');
  18. var launchEditorEndpoint = require('./launchEditorEndpoint');
  19. var formatWebpackMessages = require('./formatWebpackMessages');
  20. var ErrorOverlay = require('react-error-overlay');
  21. ErrorOverlay.setEditorHandler(function editorHandler(errorLocation) {
  22. // Keep this sync with errorOverlayMiddleware.js
  23. fetch(
  24. launchEditorEndpoint +
  25. '?fileName=' +
  26. window.encodeURIComponent(errorLocation.fileName) +
  27. '&lineNumber=' +
  28. window.encodeURIComponent(errorLocation.lineNumber || 1) +
  29. '&colNumber=' +
  30. window.encodeURIComponent(errorLocation.colNumber || 1)
  31. );
  32. });
  33. // We need to keep track of if there has been a runtime error.
  34. // Essentially, we cannot guarantee application state was not corrupted by the
  35. // runtime error. To prevent confusing behavior, we forcibly reload the entire
  36. // application. This is handled below when we are notified of a compile (code
  37. // change).
  38. // See https://github.com/facebook/create-react-app/issues/3096
  39. var hadRuntimeError = false;
  40. ErrorOverlay.startReportingRuntimeErrors({
  41. onError: function() {
  42. hadRuntimeError = true;
  43. },
  44. filename: '/static/js/bundle.js',
  45. });
  46. if (module.hot && typeof module.hot.dispose === 'function') {
  47. module.hot.dispose(function() {
  48. // TODO: why do we need this?
  49. ErrorOverlay.stopReportingRuntimeErrors();
  50. });
  51. }
  52. // Connect to WebpackDevServer via a socket.
  53. var connection = new SockJS(
  54. url.format({
  55. protocol: window.location.protocol,
  56. hostname: window.location.hostname,
  57. port: window.location.port,
  58. // Hardcoded in WebpackDevServer
  59. pathname: '/sockjs-node',
  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. ErrorOverlay.dismissBuildError();
  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. // Attempt to apply hot updates or reload.
  125. if (isHotUpdate) {
  126. tryApplyUpdates(function onSuccessfulHotUpdate() {
  127. // Only print warnings if we aren't refreshing the page.
  128. // Otherwise they'll disappear right away anyway.
  129. printWarnings();
  130. // Only dismiss it when we're sure it's a hot update.
  131. // Otherwise it would flicker right before the reload.
  132. ErrorOverlay.dismissBuildError();
  133. });
  134. } else {
  135. // Print initial warnings immediately.
  136. printWarnings();
  137. }
  138. }
  139. // Compilation with errors (e.g. syntax error or missing modules).
  140. function handleErrors(errors) {
  141. clearOutdatedErrors();
  142. isFirstCompilation = false;
  143. hasCompileErrors = true;
  144. // "Massage" webpack messages.
  145. var formatted = formatWebpackMessages({
  146. errors: errors,
  147. warnings: [],
  148. });
  149. // Only show the first error.
  150. ErrorOverlay.reportBuildError(formatted.errors[0]);
  151. // Also log them to the console.
  152. if (typeof console !== 'undefined' && typeof console.error === 'function') {
  153. for (var i = 0; i < formatted.errors.length; i++) {
  154. console.error(stripAnsi(formatted.errors[i]));
  155. }
  156. }
  157. // Do not attempt to reload now.
  158. // We will reload on next success instead.
  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. if (err || !updatedModules || hadRuntimeError) {
  213. window.location.reload();
  214. return;
  215. }
  216. if (typeof onHotUpdateSuccess === 'function') {
  217. // Maybe we want to do something.
  218. onHotUpdateSuccess();
  219. }
  220. if (isUpdateAvailable()) {
  221. // While we were updating, there was a new update! Do it again.
  222. tryApplyUpdates();
  223. }
  224. }
  225. // https://webpack.github.io/docs/hot-module-replacement.html#check
  226. var result = module.hot.check(/* autoApply */ true, handleApplyUpdates);
  227. // // Webpack 2 returns a Promise instead of invoking a callback
  228. if (result && result.then) {
  229. result.then(
  230. function(updatedModules) {
  231. handleApplyUpdates(null, updatedModules);
  232. },
  233. function(err) {
  234. handleApplyUpdates(err, null);
  235. }
  236. );
  237. }
  238. }