webpackHotDevClient.js 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

10
11
'use strict';

12
13
14
15
16
17
18
19
20
21
22
23
24
25
// This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js

// It only supports their simplest configuration (hot updates on same server).
// It makes some opinionated choices on top, like adding a syntax error overlay
// that looks similar to our console output. The error overlay is inspired by:
// https://github.com/glenjamin/webpack-hot-middleware

var SockJS = require('sockjs-client');
var stripAnsi = require('strip-ansi');
var url = require('url');
var formatWebpackMessages = require('./formatWebpackMessages');
var Entities = require('html-entities').AllHtmlEntities;
26
var ansiHTML = require('./ansiHTML');
27
28
var entities = new Entities();

29
30
31
32
function createOverlayIframe(onIframeLoad) {
  var iframe = document.createElement('iframe');
  iframe.id = 'react-dev-utils-webpack-hot-dev-client-overlay';
  iframe.src = 'about:blank';
33
34
35
36
37
38
39
40
  iframe.style.position = 'fixed';
  iframe.style.left = 0;
  iframe.style.top = 0;
  iframe.style.right = 0;
  iframe.style.bottom = 0;
  iframe.style.width = '100vw';
  iframe.style.height = '100vh';
  iframe.style.border = 'none';
41
  iframe.style.zIndex = 2147483647;
42
43
44
45
46
  iframe.onload = onIframeLoad;
  return iframe;
}

function addOverlayDivTo(iframe) {
47
48
49
50
51
52
53
54
55
56
57
58
  // TODO: unify these styles with react-error-overlay
  iframe.contentDocument.body.style.margin = 0;
  iframe.contentDocument.body.style.maxWidth = '100vw';

  var outerDiv = iframe.contentDocument.createElement('div');
  outerDiv.id = 'react-dev-utils-webpack-hot-dev-client-overlay-div';
  outerDiv.style.width = '100%';
  outerDiv.style.height = '100%';
  outerDiv.style.boxSizing = 'border-box';
  outerDiv.style.textAlign = 'center';
  outerDiv.style.backgroundColor = 'rgb(255, 255, 255)';

59
  var div = iframe.contentDocument.createElement('div');
60
61
62
63
64
65
66
67
68
  div.style.position = 'relative';
  div.style.display = 'inline-flex';
  div.style.flexDirection = 'column';
  div.style.height = '100%';
  div.style.width = '1024px';
  div.style.maxWidth = '100%';
  div.style.overflowX = 'hidden';
  div.style.overflowY = 'auto';
  div.style.padding = '0.5rem';
69
  div.style.boxSizing = 'border-box';
70
  div.style.textAlign = 'left';
71
72
  div.style.fontFamily = 'Consolas, Menlo, monospace';
  div.style.fontSize = '11px';
73
  div.style.whiteSpace = 'pre-wrap';
74
75
76
77
78
79
  div.style.wordBreak = 'break-word';
  div.style.lineHeight = '1.5';
  div.style.color = 'rgb(41, 50, 56)';

  outerDiv.appendChild(div);
  iframe.contentDocument.body.appendChild(outerDiv);
80
81
82
  return div;
}

83
84
85
86
87
function overlayHeaderStyle() {
  return 'font-size: 2em;' +
    'font-family: sans-serif;' +
    'color: rgb(206, 17, 38);' +
    'white-space: pre-wrap;' +
88
    'margin: 0 2rem 0.75rem 0px;' +
89
90
91
92
93
    'flex: 0 0 auto;' +
    'max-height: 35%;' +
    'overflow: auto;';
}

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
var overlayIframe = null;
var overlayDiv = null;
var lastOnOverlayDivReady = null;

function ensureOverlayDivExists(onOverlayDivReady) {
  if (overlayDiv) {
    // Everything is ready, call the callback right away.
    onOverlayDivReady(overlayDiv);
    return;
  }

  // Creating an iframe may be asynchronous so we'll schedule the callback.
  // In case of multiple calls, last callback wins.
  lastOnOverlayDivReady = onOverlayDivReady;

  if (overlayIframe) {
    // We're already creating it.
    return;
  }

  // Create iframe and, when it is ready, a div inside it.
  overlayIframe = createOverlayIframe(function onIframeLoad() {
    overlayDiv = addOverlayDivTo(overlayIframe);
    // Now we can talk!
    lastOnOverlayDivReady(overlayDiv);
  });

Brian Ng's avatar
Brian Ng committed
121
  // Zalgo alert: onIframeLoad() will be called either synchronously
122
123
124
125
126
127
128
  // or asynchronously depending on the browser.
  // We delay adding it so `overlayIframe` is set when `onIframeLoad` fires.
  document.body.appendChild(overlayIframe);
}

function showErrorOverlay(message) {
  ensureOverlayDivExists(function onOverlayDivReady(overlayDiv) {
129
130
131
    // TODO: unify this with our runtime overlay
    overlayDiv.innerHTML = '<div style="' +
      overlayHeaderStyle() +
132
      '">Failed to compile</div>' +
133
      '<pre style="' +
134
      'display: block; padding: 0.5em; margin-top: 0; ' +
135
136
137
138
139
140
141
142
143
      'margin-bottom: 0.5em; overflow-x: auto; white-space: pre-wrap; ' +
      'border-radius: 0.25rem; background-color: rgba(206, 17, 38, 0.05)">' +
      '<code style="font-family: Consolas, Menlo, monospace;">' +
      ansiHTML(entities.encode(message)) +
      '</code></pre>' +
      '<div style="' +
      'font-family: sans-serif; color: rgb(135, 142, 145); margin-top: 0.5rem; ' +
      'flex: 0 0 auto">' +
      'This error occurred during the build time and cannot be dismissed.</div>';
144
  });
145
146
}

147
function destroyErrorOverlay() {
148
149
150
151
152
153
154
155
156
157
158
159
  if (!overlayDiv) {
    // It is not there in the first place.
    return;
  }

  // Clean up and reset internal state.
  document.body.removeChild(overlayIframe);
  overlayDiv = null;
  overlayIframe = null;
  lastOnOverlayDivReady = null;
}

160
// Connect to WebpackDevServer via a socket.
161
162
163
164
165
166
167
168
169
var connection = new SockJS(
  url.format({
    protocol: window.location.protocol,
    hostname: window.location.hostname,
    port: window.location.port,
    // Hardcoded in WebpackDevServer
    pathname: '/sockjs-node',
  })
);
170
171
172
173
174
175
176
177
178

// Unlike WebpackDevServer client, we won't try to reconnect
// to avoid spamming the console. Disconnect usually happens
// when developer stops the server.
connection.onclose = function() {
  console.info(
    'The development server has disconnected.\nRefresh the page if necessary.'
  );
};
179
180
181
182

// Remember some state related to hot module replacement.
var isFirstCompilation = true;
var mostRecentCompilationHash = null;
183
184
185
186
187
188
189
190
var hasCompileErrors = false;

function clearOutdatedErrors() {
  // Clean up outdated compile errors, if any.
  if (hasCompileErrors && typeof console.clear === 'function') {
    console.clear();
  }
}
191
192
193

// Successful compilation.
function handleSuccess() {
194
195
  clearOutdatedErrors();

196
197
  var isHotUpdate = !isFirstCompilation;
  isFirstCompilation = false;
198
  hasCompileErrors = false;
199
200
201

  // Attempt to apply hot updates or reload.
  if (isHotUpdate) {
202
203
204
205
206
    tryApplyUpdates(function onHotUpdateSuccess() {
      // Only destroy it when we're sure it's a hot update.
      // Otherwise it would flicker right before the reload.
      destroyErrorOverlay();
    });
207
208
209
210
211
  }
}

// Compilation with warnings (e.g. ESLint).
function handleWarnings(warnings) {
212
213
  clearOutdatedErrors();

214
215
  var isHotUpdate = !isFirstCompilation;
  isFirstCompilation = false;
216
  hasCompileErrors = false;
217
218
219

  function printWarnings() {
    // Print warnings to the console.
220
221
222
223
224
225
226
    var formatted = formatWebpackMessages({
      warnings: warnings,
      errors: [],
    });

    for (var i = 0; i < formatted.warnings.length; i++) {
      console.warn(stripAnsi(formatted.warnings[i]));
227
228
229
230
231
232
233
234
235
    }
  }

  // Attempt to apply hot updates or reload.
  if (isHotUpdate) {
    tryApplyUpdates(function onSuccessfulHotUpdate() {
      // Only print warnings if we aren't refreshing the page.
      // Otherwise they'll disappear right away anyway.
      printWarnings();
236
237
238
      // Only destroy it when we're sure it's a hot update.
      // Otherwise it would flicker right before the reload.
      destroyErrorOverlay();
239
240
241
242
243
244
245
246
247
    });
  } else {
    // Print initial warnings immediately.
    printWarnings();
  }
}

// Compilation with errors (e.g. syntax error or missing modules).
function handleErrors(errors) {
248
249
  clearOutdatedErrors();

250
  isFirstCompilation = false;
251
  hasCompileErrors = true;
252
253
254
255

  // "Massage" webpack messages.
  var formatted = formatWebpackMessages({
    errors: errors,
256
    warnings: [],
257
258
259
260
  });

  // Only show the first error.
  showErrorOverlay(formatted.errors[0]);
261
262
263
264
265
266

  // Also log them to the console.
  for (var i = 0; i < formatted.errors.length; i++) {
    console.error(stripAnsi(formatted.errors[i]));
  }

267
268
269
270
271
272
273
274
275
276
277
278
279
280
  // Do not attempt to reload now.
  // We will reload on next success instead.
}

// There is a newer version of the code available.
function handleAvailableHash(hash) {
  // Update last known compilation hash.
  mostRecentCompilationHash = hash;
}

// Handle messages from the server.
connection.onmessage = function(e) {
  var message = JSON.parse(e.data);
  switch (message.type) {
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    case 'hash':
      handleAvailableHash(message.data);
      break;
    case 'still-ok':
    case 'ok':
      handleSuccess();
      break;
    case 'content-changed':
      // Triggered when a file from `contentBase` changed.
      window.location.reload();
      break;
    case 'warnings':
      handleWarnings(message.data);
      break;
    case 'errors':
      handleErrors(message.data);
      break;
    default:
299
300
    // Do nothing.
  }
301
};
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327

// Is there a newer version of this code available?
function isUpdateAvailable() {
  /* globals __webpack_hash__ */
  // __webpack_hash__ is the hash of the current compilation.
  // It's a global variable injected by Webpack.
  return mostRecentCompilationHash !== __webpack_hash__;
}

// Webpack disallows updates in other states.
function canApplyUpdates() {
  return module.hot.status() === 'idle';
}

// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdates(onHotUpdateSuccess) {
  if (!module.hot) {
    // HotModuleReplacementPlugin is not in Webpack configuration.
    window.location.reload();
    return;
  }

  if (!isUpdateAvailable() || !canApplyUpdates()) {
    return;
  }

328
  function handleApplyUpdates(err, updatedModules) {
329
330
331
332
333
334
335
336
337
338
339
340
341
342
    if (err || !updatedModules) {
      window.location.reload();
      return;
    }

    if (typeof onHotUpdateSuccess === 'function') {
      // Maybe we want to do something.
      onHotUpdateSuccess();
    }

    if (isUpdateAvailable()) {
      // While we were updating, there was a new update! Do it again.
      tryApplyUpdates();
    }
343
344
345
  }

  // https://webpack.github.io/docs/hot-module-replacement.html#check
346
  var result = module.hot.check(/* autoApply */ true, handleApplyUpdates);
347
348
349
350
351
352
353
354
355
356
357
358

  // // Webpack 2 returns a Promise instead of invoking a callback
  if (result && result.then) {
    result.then(
      function(updatedModules) {
        handleApplyUpdates(null, updatedModules);
      },
      function(err) {
        handleApplyUpdates(err, null);
      }
    );
  }
359
}