index.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. },
  123. ok: function ok() {
  124. sendMsg('Ok');
  125. if (useWarningOverlay || useErrorOverlay) overlay.clear();
  126. if (initial) return initial = false; // eslint-disable-line no-return-assign
  127. reloadApp();
  128. },
  129. 'content-changed': function contentChanged() {
  130. log.info('[WDS] Content base changed. Reloading...');
  131. self.location.reload();
  132. },
  133. warnings: function warnings(_warnings) {
  134. log.warn('[WDS] Warnings while compiling.');
  135. var strippedWarnings = _warnings.map(function (warning) {
  136. return stripAnsi(warning);
  137. });
  138. sendMsg('Warnings', strippedWarnings);
  139. for (var i = 0; i < strippedWarnings.length; i++) {
  140. log.warn(strippedWarnings[i]);
  141. }
  142. if (useWarningOverlay) overlay.showMessage(_warnings);
  143. if (initial) return initial = false; // eslint-disable-line no-return-assign
  144. reloadApp();
  145. },
  146. errors: function errors(_errors) {
  147. log.error('[WDS] Errors while compiling. Reload prevented.');
  148. var strippedErrors = _errors.map(function (error) {
  149. return stripAnsi(error);
  150. });
  151. sendMsg('Errors', strippedErrors);
  152. for (var i = 0; i < strippedErrors.length; i++) {
  153. log.error(strippedErrors[i]);
  154. }
  155. if (useErrorOverlay) overlay.showMessage(_errors);
  156. initial = false;
  157. },
  158. error: function error(_error) {
  159. log.error(_error);
  160. },
  161. close: function close() {
  162. log.error('[WDS] Disconnected!');
  163. sendMsg('Close');
  164. }
  165. };
  166. var hostname = urlParts.hostname;
  167. var protocol = urlParts.protocol;
  168. // check ipv4 and ipv6 `all hostname`
  169. if (hostname === '0.0.0.0' || hostname === '::') {
  170. // why do we need this check?
  171. // hostname n/a for file protocol (example, when using electron, ionic)
  172. // see: https://github.com/webpack/webpack-dev-server/pull/384
  173. // eslint-disable-next-line no-bitwise
  174. if (self.location.hostname && !!~self.location.protocol.indexOf('http')) {
  175. hostname = self.location.hostname;
  176. }
  177. }
  178. // `hostname` can be empty when the script path is relative. In that case, specifying
  179. // a protocol would result in an invalid URL.
  180. // When https is used in the app, secure websockets are always necessary
  181. // because the browser doesn't accept non-secure websockets.
  182. if (hostname && (self.location.protocol === 'https:' || urlParts.hostname === '0.0.0.0')) {
  183. protocol = self.location.protocol;
  184. }
  185. var socketUrl = url.format({
  186. protocol: protocol,
  187. auth: urlParts.auth,
  188. hostname: hostname,
  189. port: urlParts.port,
  190. pathname: urlParts.path == null || urlParts.path === '/' ? '/sockjs-node' : urlParts.path
  191. });
  192. socket(socketUrl, onSocketMsg);
  193. var isUnloading = false;
  194. self.addEventListener('beforeunload', function () {
  195. isUnloading = true;
  196. });
  197. function reloadApp() {
  198. if (isUnloading || !hotReload) {
  199. return;
  200. }
  201. if (_hot) {
  202. log.info('[WDS] App hot update...');
  203. // eslint-disable-next-line global-require
  204. var hotEmitter = require('webpack/hot/emitter');
  205. hotEmitter.emit('webpackHotUpdate', currentHash);
  206. if (typeof self !== 'undefined' && self.window) {
  207. // broadcast update to window
  208. self.postMessage('webpackHotUpdate' + currentHash, '*');
  209. }
  210. } else {
  211. var rootWindow = self;
  212. // use parent window for reload (in case we're in an iframe with no valid src)
  213. var intervalId = self.setInterval(function () {
  214. if (rootWindow.location.protocol !== 'about:') {
  215. // reload immediately if protocol is valid
  216. applyReload(rootWindow, intervalId);
  217. } else {
  218. rootWindow = rootWindow.parent;
  219. if (rootWindow.parent === rootWindow) {
  220. // if parent equals current window we've reached the root which would continue forever, so trigger a reload anyways
  221. applyReload(rootWindow, intervalId);
  222. }
  223. }
  224. });
  225. }
  226. function applyReload(rootWindow, intervalId) {
  227. clearInterval(intervalId);
  228. log.info('[WDS] App updated. Reloading...');
  229. rootWindow.location.reload();
  230. }
  231. }