index.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. 'use strict';
  2. /* global __resourceQuery WorkerGlobalScope self */
  3. /* eslint prefer-destructuring: off */
  4. var url = require('url');
  5. var stripAnsi = require('strip-ansi');
  6. var log = require('loglevel').getLogger('webpack-dev-server');
  7. var socket = require('./socket');
  8. var overlay = require('./overlay');
  9. function getCurrentScriptSource() {
  10. // `document.currentScript` is the most accurate way to find the current script,
  11. // but is not supported in all browsers.
  12. if (document.currentScript) {
  13. return document.currentScript.getAttribute('src');
  14. }
  15. // Fall back to getting all scripts in the document.
  16. var scriptElements = document.scripts || [];
  17. var currentScript = scriptElements[scriptElements.length - 1];
  18. if (currentScript) {
  19. return currentScript.getAttribute('src');
  20. }
  21. // Fail as there was no script to use.
  22. throw new Error('[WDS] Failed to get current script source.');
  23. }
  24. var urlParts = void 0;
  25. var hotReload = true;
  26. if (typeof window !== 'undefined') {
  27. var qs = window.location.search.toLowerCase();
  28. hotReload = qs.indexOf('hotreload=false') === -1;
  29. }
  30. if (typeof __resourceQuery === 'string' && __resourceQuery) {
  31. // If this bundle is inlined, use the resource query to get the correct url.
  32. urlParts = url.parse(__resourceQuery.substr(1));
  33. } else {
  34. // Else, get the url from the <script> this file was called with.
  35. var scriptHost = getCurrentScriptSource();
  36. // eslint-disable-next-line no-useless-escape
  37. scriptHost = scriptHost.replace(/\/[^\/]+$/, '');
  38. urlParts = url.parse(scriptHost || '/', false, true);
  39. }
  40. if (!urlParts.port || urlParts.port === '0') {
  41. urlParts.port = self.location.port;
  42. }
  43. var _hot = false;
  44. var initial = true;
  45. var currentHash = '';
  46. var useWarningOverlay = false;
  47. var useErrorOverlay = false;
  48. var useProgress = false;
  49. var INFO = 'info';
  50. var WARNING = 'warning';
  51. var ERROR = 'error';
  52. var NONE = 'none';
  53. // Set the default log level
  54. log.setDefaultLevel(INFO);
  55. // Send messages to the outside, so plugins can consume it.
  56. function sendMsg(type, data) {
  57. if (typeof self !== 'undefined' && (typeof WorkerGlobalScope === 'undefined' || !(self instanceof WorkerGlobalScope))) {
  58. self.postMessage({
  59. type: 'webpack' + type,
  60. data: data
  61. }, '*');
  62. }
  63. }
  64. var onSocketMsg = {
  65. hot: function hot() {
  66. _hot = true;
  67. log.info('[WDS] Hot Module Replacement enabled.');
  68. },
  69. invalid: function invalid() {
  70. log.info('[WDS] App updated. Recompiling...');
  71. // fixes #1042. overlay doesn't clear if errors are fixed but warnings remain.
  72. if (useWarningOverlay || useErrorOverlay) overlay.clear();
  73. sendMsg('Invalid');
  74. },
  75. hash: function hash(_hash) {
  76. currentHash = _hash;
  77. },
  78. 'still-ok': function stillOk() {
  79. log.info('[WDS] Nothing changed.');
  80. if (useWarningOverlay || useErrorOverlay) overlay.clear();
  81. sendMsg('StillOk');
  82. },
  83. 'log-level': function logLevel(level) {
  84. var hotCtx = require.context('webpack/hot', false, /^\.\/log$/);
  85. if (hotCtx.keys().indexOf('./log') !== -1) {
  86. hotCtx('./log').setLogLevel(level);
  87. }
  88. switch (level) {
  89. case INFO:
  90. case ERROR:
  91. log.setLevel(level);
  92. break;
  93. case WARNING:
  94. // loglevel's warning name is different from webpack's
  95. log.setLevel('warn');
  96. break;
  97. case NONE:
  98. log.disableAll();
  99. break;
  100. default:
  101. log.error('[WDS] Unknown clientLogLevel \'' + level + '\'');
  102. }
  103. },
  104. overlay: function overlay(value) {
  105. if (typeof document !== 'undefined') {
  106. if (typeof value === 'boolean') {
  107. useWarningOverlay = false;
  108. useErrorOverlay = value;
  109. } else if (value) {
  110. useWarningOverlay = value.warnings;
  111. useErrorOverlay = value.errors;
  112. }
  113. }
  114. },
  115. progress: function progress(_progress) {
  116. if (typeof document !== 'undefined') {
  117. useProgress = _progress;
  118. }
  119. },
  120. 'progress-update': function progressUpdate(data) {
  121. if (useProgress) log.info('[WDS] ' + data.percent + '% - ' + data.msg + '.');
  122. sendMsg('Progress', data);
  123. },
  124. ok: function ok() {
  125. sendMsg('Ok');
  126. if (useWarningOverlay || useErrorOverlay) overlay.clear();
  127. if (initial) return initial = false; // eslint-disable-line no-return-assign
  128. reloadApp();
  129. },
  130. 'content-changed': function contentChanged() {
  131. log.info('[WDS] Content base changed. Reloading...');
  132. self.location.reload();
  133. },
  134. warnings: function warnings(_warnings) {
  135. log.warn('[WDS] Warnings while compiling.');
  136. var strippedWarnings = _warnings.map(function (warning) {
  137. return stripAnsi(warning);
  138. });
  139. sendMsg('Warnings', strippedWarnings);
  140. for (var i = 0; i < strippedWarnings.length; i++) {
  141. log.warn(strippedWarnings[i]);
  142. }
  143. if (useWarningOverlay) overlay.showMessage(_warnings);
  144. if (initial) return initial = false; // eslint-disable-line no-return-assign
  145. reloadApp();
  146. },
  147. errors: function errors(_errors) {
  148. log.error('[WDS] Errors while compiling. Reload prevented.');
  149. var strippedErrors = _errors.map(function (error) {
  150. return stripAnsi(error);
  151. });
  152. sendMsg('Errors', strippedErrors);
  153. for (var i = 0; i < strippedErrors.length; i++) {
  154. log.error(strippedErrors[i]);
  155. }
  156. if (useErrorOverlay) overlay.showMessage(_errors);
  157. initial = false;
  158. },
  159. error: function error(_error) {
  160. log.error(_error);
  161. },
  162. close: function close() {
  163. log.error('[WDS] Disconnected!');
  164. sendMsg('Close');
  165. }
  166. };
  167. var hostname = urlParts.hostname;
  168. var protocol = urlParts.protocol;
  169. // check ipv4 and ipv6 `all hostname`
  170. if (hostname === '0.0.0.0' || hostname === '::') {
  171. // why do we need this check?
  172. // hostname n/a for file protocol (example, when using electron, ionic)
  173. // see: https://github.com/webpack/webpack-dev-server/pull/384
  174. // eslint-disable-next-line no-bitwise
  175. if (self.location.hostname && !!~self.location.protocol.indexOf('http')) {
  176. hostname = self.location.hostname;
  177. }
  178. }
  179. // `hostname` can be empty when the script path is relative. In that case, specifying
  180. // a protocol would result in an invalid URL.
  181. // When https is used in the app, secure websockets are always necessary
  182. // because the browser doesn't accept non-secure websockets.
  183. if (hostname && (self.location.protocol === 'https:' || urlParts.hostname === '0.0.0.0')) {
  184. protocol = self.location.protocol;
  185. }
  186. var socketUrl = url.format({
  187. protocol: protocol,
  188. auth: urlParts.auth,
  189. hostname: hostname,
  190. port: urlParts.port,
  191. pathname: urlParts.path == null || urlParts.path === '/' ? '/sockjs-node' : urlParts.path
  192. });
  193. socket(socketUrl, onSocketMsg);
  194. var isUnloading = false;
  195. self.addEventListener('beforeunload', function () {
  196. isUnloading = true;
  197. });
  198. function reloadApp() {
  199. if (isUnloading || !hotReload) {
  200. return;
  201. }
  202. if (_hot) {
  203. log.info('[WDS] App hot update...');
  204. // eslint-disable-next-line global-require
  205. var hotEmitter = require('webpack/hot/emitter');
  206. hotEmitter.emit('webpackHotUpdate', currentHash);
  207. if (typeof self !== 'undefined' && self.window) {
  208. // broadcast update to window
  209. self.postMessage('webpackHotUpdate' + currentHash, '*');
  210. }
  211. } else {
  212. var rootWindow = self;
  213. // use parent window for reload (in case we're in an iframe with no valid src)
  214. var intervalId = self.setInterval(function () {
  215. if (rootWindow.location.protocol !== 'about:') {
  216. // reload immediately if protocol is valid
  217. applyReload(rootWindow, intervalId);
  218. } else {
  219. rootWindow = rootWindow.parent;
  220. if (rootWindow.parent === rootWindow) {
  221. // if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
  222. applyReload(rootWindow, intervalId);
  223. }
  224. }
  225. });
  226. }
  227. function applyReload(rootWindow, intervalId) {
  228. clearInterval(intervalId);
  229. log.info('[WDS] App updated. Reloading...');
  230. rootWindow.location.reload();
  231. }
  232. }