formatWebpackMessages.js 6.14 KB
Newer Older
1
2
3
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
Sophie Alpert's avatar
Sophie Alpert committed
4
5
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
6
7
 */

8
9
'use strict';

10
11
12
// WARNING: this code is untranspiled and is used in browser too.
// Please make sure any changes are in ES5 or contribute a Babel compile step.

13
// Some custom utilities to prettify Webpack output.
14
15
16
// This is quite hacky and hopefully won't be needed when Webpack fixes this.
// https://github.com/webpack/webpack/issues/2878

17
var chalk = require('chalk');
18
var friendlySyntaxErrorLabel = 'Syntax error:';
19

20
21
22
function isLikelyASyntaxError(message) {
  return message.indexOf(friendlySyntaxErrorLabel) !== -1;
}
23
24

// Cleans up webpack error messages.
Joe Haddad's avatar
Joe Haddad committed
25
// eslint-disable-next-line no-unused-vars
26
function formatMessage(message, isError) {
27
28
  var lines = message.split('\n');

29
30
31
32
33
34
  // Strip `WorkerError` header off message before parsing
  // https://github.com/webpack-contrib/thread-loader/blob/6fb5daff313c4839196cf533bdcdf14815a386d2/src/WorkerError.js
  lines = lines.filter(function(message) {
    return message.indexOf('Thread Loader (Worker') === -1;
  });

35
36
37
38
39
  // Add empty line for errors from third-party webpack plugins
  if (lines.length < 2) {
    lines[1] = '';
  }

40
41
42
43
44
45
46
47
48
  // Strip `ModuleWarning` head off message before parsing (because of ESLint)
  // https://github.com/webpack/webpack/blob/c77030573de96b8293c69dd396492f8e2d46561e/lib/ModuleWarning.js
  var moduleWarningPrefix = 'Module Warning: ';
  if (lines[1].indexOf(moduleWarningPrefix) === 0) {
    lines[1] = lines[1].slice(moduleWarningPrefix.length);
  } else if (lines[1].match(/Module Warning \(from.*?\):/)) {
    lines.splice(1, 1);
  }

49
50
51
52
53
54
55
56
57
  // Strip `ModuleError` header off message before parsing
  // https://github.com/webpack/webpack/blob/c77030573de96b8293c69dd396492f8e2d46561e/lib/ModuleError.js
  var moduleErrorPrefix = 'Module Error: ';
  if (lines[1].indexOf(moduleErrorPrefix) === 0) {
    lines[1] = lines[1].slice(moduleErrorPrefix.length);
  } else if (lines[1].match(/Module Error \(from.*?\):/)) {
    lines.splice(1, 1);
  }

Joe Haddad's avatar
Joe Haddad committed
58
  // Simplify `ModuleBuildError` before parsing (these may be nested so we use a while loop)
59
  // https://github.com/webpack/webpack/blob/c77030573de96b8293c69dd396492f8e2d46561e/lib/ModuleBuildError.js
Joe Haddad's avatar
Joe Haddad committed
60
61
62
63
  while (
    lines.length > 2 &&
    lines[1].match(/Module build failed \(from.*?\):/)
  ) {
64
65
66
67
    lines.splice(1, 1);
    lines[1] = 'Module build failed: ' + lines[1];
  }

68
69
70
71
72
  if (lines.length > 2 && lines[1] === '') {
    // Remove extra newline.
    lines.splice(1, 1);
  }

73
74
75
76
77
78
79
80
81
  // Remove webpack-specific loader notation from filename.
  // Before:
  // ./~/css-loader!./~/postcss-loader!./src/App.css
  // After:
  // ./src/App.css
  if (lines[0].lastIndexOf('!') !== -1) {
    lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
  }

82
83
84
85
86
87
88
89
90
  lines = lines.filter(function(line) {
    // Webpack adds a list of entry points to warning messages:
    //  @ ./src/index.js
    //  @ multi react-scripts/~/react-dev-utils/webpackHotDevClient.js ...
    // It is misleading (and unrelated to the warnings) so we clean it up.
    // It is only useful for syntax errors but we have beautiful frames for them.
    return line.indexOf(' @ ') !== 0;
  });

91
92
93
94
95
96
  // line #0 is filename
  // line #1 is the main error message
  if (!lines[0] || !lines[1]) {
    return lines.join('\n');
  }

97
98
99
100
101
  // Cleans up verbose "module not found" messages for files and packages.
  if (lines[1].indexOf('Module not found: ') === 0) {
    lines = [
      lines[0],
      // Clean up message because "Module not found: " is descriptive enough.
102
103
104
      lines[1]
        .replace("Cannot resolve 'file' or 'directory' ", '')
        .replace('Cannot resolve module ', '')
105
106
        .replace('Error: ', '')
        .replace('[CaseSensitivePathsPlugin] ', ''),
107
    ];
108
109
  }

110
111
112
113
114
115
116
  if (lines[1].match(/Cannot find module.+node-sass/)) {
    lines[1] =
      'To import Sass files in this project, you need to install node-sass.\n';
    lines[1] +=
      'Please run `npm i node-sass --save` or `yarn add node-sass` inside your workspace.';
  }

117
118
  // Cleans up syntax error messages.
  if (lines[1].indexOf('Module build failed: ') === 0) {
Joe Haddad's avatar
Joe Haddad committed
119
120
121
122
    lines[1] = lines[1].replace(
      'Module build failed: Syntax Error ',
      friendlySyntaxErrorLabel
    );
123
    lines[1] = lines[1].replace(
124
125
      /Module build failed: .*?: /,
      friendlySyntaxErrorLabel + ' '
126
    );
Joe Haddad's avatar
Joe Haddad committed
127
128
129
130
131
132
133
134
135
    lines[1] = lines[1].trim();

    if (lines[1] === friendlySyntaxErrorLabel && lines[2] === '') {
      lines.splice(2, 1);
      if (lines.length > 2) {
        lines[1] += ' ' + lines[2];
        lines.splice(2, 1);
      }
    }
136
137
  }

138
139
  // Clean up export errors.
  // TODO: we should really send a PR to Webpack for this.
Joe Haddad's avatar
Joe Haddad committed
140
  var exportError = /\s*(.*?)\s*(?:")?export '(.+?)' was not found in '(.+?)'/;
141
142
143
  if (lines[1].match(exportError)) {
    lines[1] = lines[1].replace(
      exportError,
Joe Haddad's avatar
Joe Haddad committed
144
      "$1  '$3' does not contain an export named '$2'."
145
146
    );
  }
147

148
  lines[0] = chalk.inverse(lines[0]);
149

150
151
  // Reassemble the message.
  message = lines.join('\n');
152
153
154
  // Internal stacks are generally useless so we strip them... with the
  // exception of stacks containing `webpack:` because they're normally
  // from user code generated by WebPack. For more information see
155
  // https://github.com/facebook/create-react-app/pull/1050
156
  message = message.replace(
Joe Haddad's avatar
Joe Haddad committed
157
    /^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
158
    ''
159
  ); // at ... ...:x:y
Joe Haddad's avatar
Joe Haddad committed
160
  message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, ''); // at <anonymous>
161

162
  return message.trim();
163
164
}

165
166
function formatWebpackMessages(json) {
  var formattedErrors = json.errors.map(function(message) {
167
    return formatMessage(message, true);
168
169
  });
  var formattedWarnings = json.warnings.map(function(message) {
170
    return formatMessage(message, false);
171
  });
172
173
  var result = {
    errors: formattedErrors,
174
    warnings: formattedWarnings,
175
176
177
178
179
180
181
182
183
184
185
  };
  if (result.errors.some(isLikelyASyntaxError)) {
    // If there are any syntax errors, show just them.
    // This prevents a confusing ESLint parsing error
    // preceding a much more useful Babel syntax error.
    result.errors = result.errors.filter(isLikelyASyntaxError);
  }
  return result;
}

module.exports = formatWebpackMessages;