@umijs/bundler-webpack 4.0.7 → 4.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/{dist → client}/client/client.d.ts +0 -0
  2. package/client/client/client.js +172 -192
  3. package/client/constants.d.ts +15 -0
  4. package/client/constants.js +28 -19
  5. package/client/utils/formatWebpackMessages.d.ts +12 -0
  6. package/client/utils/formatWebpackMessages.js +68 -86
  7. package/dist/build.d.ts +1 -1
  8. package/dist/build.js +105 -68
  9. package/dist/cli.js +77 -69
  10. package/dist/config/_sampleFeature.js +33 -9
  11. package/dist/config/assetRules.js +45 -36
  12. package/dist/config/bundleAnalyzerPlugin.js +39 -17
  13. package/dist/config/compressPlugin.js +113 -95
  14. package/dist/config/config.d.ts +1 -0
  15. package/dist/config/config.js +204 -215
  16. package/dist/config/copyPlugin.js +58 -40
  17. package/dist/config/cssRules.js +136 -131
  18. package/dist/config/definePlugin.js +71 -35
  19. package/dist/config/detectDeadCode.js +120 -108
  20. package/dist/config/detectDeadCodePlugin.js +78 -63
  21. package/dist/config/fastRefreshPlugin.js +39 -20
  22. package/dist/config/forkTSCheckerPlugin.js +38 -19
  23. package/dist/config/harmonyLinkingErrorPlugin.js +48 -29
  24. package/dist/config/ignorePlugin.js +38 -14
  25. package/dist/config/javaScriptRules.js +146 -173
  26. package/dist/config/manifestPlugin.js +51 -15
  27. package/dist/config/miniCSSExtractPlugin.js +42 -22
  28. package/dist/config/nodePolyfill.js +65 -26
  29. package/dist/config/nodePrefixPlugin.js +36 -12
  30. package/dist/config/progressPlugin.js +37 -13
  31. package/dist/config/purgecssWebpackPlugin.js +41 -19
  32. package/dist/config/speedMeasureWebpackPlugin.js +41 -20
  33. package/dist/config/ssrPlugin.js +83 -63
  34. package/dist/config/svgRules.js +74 -46
  35. package/dist/constants.js +57 -22
  36. package/dist/dev.d.ts +1 -1
  37. package/dist/dev.js +170 -134
  38. package/dist/index.js +22 -20
  39. package/dist/loader/svgr.js +73 -54
  40. package/dist/loader/swc.js +110 -69
  41. package/dist/parcelCSS.js +31 -27
  42. package/dist/plugins/ProgressPlugin.js +66 -43
  43. package/dist/plugins/RuntimePublicPathPlugin.js +42 -23
  44. package/dist/plugins/_SamplePlugin.js +39 -14
  45. package/dist/requireHook.js +37 -27
  46. package/dist/schema.js +119 -96
  47. package/dist/server/server.d.ts +0 -1
  48. package/dist/server/server.js +214 -184
  49. package/dist/server/ws.d.ts +0 -2
  50. package/dist/server/ws.js +63 -38
  51. package/dist/swcPlugins/autoCSSModules.js +50 -31
  52. package/dist/swcPlugins/changeImportFromString.js +31 -9
  53. package/dist/swcPlugins/lockCoreJS.js +44 -20
  54. package/dist/types.js +61 -30
  55. package/dist/utils/browsersList.js +31 -8
  56. package/dist/utils/depMatch.js +63 -39
  57. package/dist/utils/formatWebpackMessages.js +93 -91
  58. package/dist/utils/getEsBuildTarget.js +32 -10
  59. package/package.json +9 -11
  60. package/compiled/fork-ts-checker-webpack-plugin/LICENSE +0 -21
  61. package/compiled/fork-ts-checker-webpack-plugin/fsevents.node +0 -0
  62. package/compiled/fork-ts-checker-webpack-plugin/index.js +0 -42
  63. package/compiled/fork-ts-checker-webpack-plugin/package.json +0 -1
  64. package/dist/client/client.js +0 -245
File without changes
@@ -1,230 +1,210 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __commonJS = (cb, mod) => function __require() {
3
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4
+ };
5
+ var __async = (__this, __arguments, generator) => {
6
+ return new Promise((resolve, reject) => {
7
+ var fulfilled = (value) => {
8
+ try {
9
+ step(generator.next(value));
10
+ } catch (e) {
11
+ reject(e);
12
+ }
13
+ };
14
+ var rejected = (value) => {
15
+ try {
16
+ step(generator.throw(value));
17
+ } catch (e) {
18
+ reject(e);
19
+ }
20
+ };
21
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
22
+ step((generator = generator.apply(__this, __arguments)).next());
23
+ });
9
24
  };
10
- import stripAnsi from '@umijs/utils/compiled/strip-ansi';
11
- // @ts-ignore
12
- import * as ErrorOverlay from 'react-error-overlay';
13
- import { MESSAGE_TYPE } from '../constants';
14
- import { formatWebpackMessages } from '../utils/formatWebpackMessages';
15
- console.log('[webpack] connecting...');
16
- function getHost() {
17
- if (process.env.SOCKET_SERVER) {
25
+
26
+ // client.ts
27
+ import stripAnsi from "@umijs/utils/compiled/strip-ansi";
28
+ import * as ErrorOverlay from "react-error-overlay";
29
+ import { MESSAGE_TYPE } from "../constants";
30
+ import { formatWebpackMessages } from "../utils/formatWebpackMessages";
31
+ var require_client = __commonJS({
32
+ "client.ts"(exports, module) {
33
+ console.log("[webpack] connecting...");
34
+ function getHost() {
35
+ if (process.env.SOCKET_SERVER) {
18
36
  return new URL(process.env.SOCKET_SERVER);
37
+ }
38
+ return location;
19
39
  }
20
- return location;
21
- }
22
- function getSocketUrl() {
23
- let h = getHost();
24
- const host = h.host;
25
- const isHttps = h.protocol === 'https:';
26
- return `${isHttps ? 'wss' : 'ws'}://${host}`;
27
- }
28
- function getPingUrl() {
29
- const h = getHost();
30
- return `${h.protocol}//${h.host}/__umi_ping`;
31
- }
32
- let pingTimer = null;
33
- let isFirstCompilation = true;
34
- let mostRecentCompilationHash = null;
35
- let hasCompileErrors = false;
36
- let hadRuntimeError = false;
37
- const pingUrl = getPingUrl();
38
- const socket = new WebSocket(getSocketUrl(), 'webpack-hmr');
39
- socket.addEventListener('message', ({ data }) => __awaiter(void 0, void 0, void 0, function* () {
40
- data = JSON.parse(data);
41
- if (data.type === 'connected') {
42
- console.log(`[webpack] connected.`);
43
- // proxy(nginx, docker) hmr ws maybe caused timeout,
44
- // so send ping package let ws keep alive.
45
- pingTimer = setInterval(() => socket.send('ping'), 30000);
40
+ function getSocketUrl() {
41
+ let h = getHost();
42
+ const host = h.host;
43
+ const isHttps = h.protocol === "https:";
44
+ return `${isHttps ? "wss" : "ws"}://${host}`;
46
45
  }
47
- else {
48
- handleMessage(data).catch(console.error);
46
+ function getPingUrl() {
47
+ const h = getHost();
48
+ return `${h.protocol}//${h.host}/__umi_ping`;
49
49
  }
50
- }));
51
- function waitForSuccessfulPing(ms = 1000) {
52
- return __awaiter(this, void 0, void 0, function* () {
53
- // eslint-disable-next-line no-constant-condition
50
+ var pingTimer = null;
51
+ var isFirstCompilation = true;
52
+ var mostRecentCompilationHash = null;
53
+ var hasCompileErrors = false;
54
+ var hadRuntimeError = false;
55
+ var pingUrl = getPingUrl();
56
+ var socket = new WebSocket(getSocketUrl(), "webpack-hmr");
57
+ socket.addEventListener("message", (_0) => __async(exports, [_0], function* ({ data }) {
58
+ data = JSON.parse(data);
59
+ if (data.type === "connected") {
60
+ console.log(`[webpack] connected.`);
61
+ pingTimer = setInterval(() => socket.send("ping"), 3e4);
62
+ } else {
63
+ handleMessage(data).catch(console.error);
64
+ }
65
+ }));
66
+ function waitForSuccessfulPing(ms = 1e3) {
67
+ return __async(this, null, function* () {
54
68
  while (true) {
55
- try {
56
- yield fetch(pingUrl);
57
- break;
58
- }
59
- catch (e) {
60
- yield new Promise((resolve) => setTimeout(resolve, ms));
61
- }
69
+ try {
70
+ yield fetch(pingUrl);
71
+ break;
72
+ } catch (e) {
73
+ yield new Promise((resolve) => setTimeout(resolve, ms));
74
+ }
62
75
  }
63
- });
64
- }
65
- socket.addEventListener('close', () => __awaiter(void 0, void 0, void 0, function* () {
66
- if (pingTimer)
76
+ });
77
+ }
78
+ socket.addEventListener("close", () => __async(exports, null, function* () {
79
+ if (pingTimer)
67
80
  clearInterval(pingTimer);
68
- console.info('[webpack] Dev server disconnected. Polling for restart...');
69
- yield waitForSuccessfulPing();
70
- location.reload();
71
- }));
72
- ErrorOverlay.startReportingRuntimeErrors({
73
- onError: function () {
81
+ console.info("[webpack] Dev server disconnected. Polling for restart...");
82
+ yield waitForSuccessfulPing();
83
+ location.reload();
84
+ }));
85
+ ErrorOverlay.startReportingRuntimeErrors({
86
+ onError: function() {
74
87
  hadRuntimeError = true;
75
- },
76
- filename: '/static/js/bundle.js',
77
- });
78
- // @ts-ignore
79
- if (module.hot && typeof module.hot.dispose === 'function') {
80
- // @ts-ignore
81
- module.hot.dispose(function () {
82
- // TODO: why do we need this?
83
- ErrorOverlay.stopReportingRuntimeErrors();
88
+ },
89
+ filename: "/static/js/bundle.js"
84
90
  });
85
- }
86
- // There is a newer version of the code available.
87
- function handleAvailableHash(hash) {
88
- // Update last known compilation hash.
89
- mostRecentCompilationHash = hash;
90
- }
91
- function handleSuccess() {
92
- const isHotUpdate = !isFirstCompilation;
93
- isFirstCompilation = false;
94
- hasCompileErrors = false;
95
- // Attempt to apply hot updates or reload.
96
- if (isHotUpdate) {
91
+ if (module.hot && typeof module.hot.dispose === "function") {
92
+ module.hot.dispose(function() {
93
+ ErrorOverlay.stopReportingRuntimeErrors();
94
+ });
95
+ }
96
+ function handleAvailableHash(hash) {
97
+ mostRecentCompilationHash = hash;
98
+ }
99
+ function handleSuccess() {
100
+ const isHotUpdate = !isFirstCompilation;
101
+ isFirstCompilation = false;
102
+ hasCompileErrors = false;
103
+ if (isHotUpdate) {
97
104
  tryApplyUpdates(function onHotUpdateSuccess() {
98
- // Only dismiss it when we're sure it's a hot update.
99
- // Otherwise it would flicker right before the reload.
100
- tryDismissErrorOverlay();
105
+ tryDismissErrorOverlay();
101
106
  });
107
+ }
102
108
  }
103
- }
104
- function handleWarnings(warnings) {
105
- const isHotUpdate = !isFirstCompilation;
106
- isFirstCompilation = false;
107
- hasCompileErrors = false;
108
- const formatted = formatWebpackMessages({
109
+ function handleWarnings(warnings) {
110
+ const isHotUpdate = !isFirstCompilation;
111
+ isFirstCompilation = false;
112
+ hasCompileErrors = false;
113
+ const formatted = formatWebpackMessages({
109
114
  warnings,
110
- errors: [],
111
- });
112
- // print warnings
113
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
115
+ errors: []
116
+ });
117
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
114
118
  for (let i = 0; i < formatted.warnings.length; i++) {
115
- if (i === 5) {
116
- console.warn('There were more warnings in other files.\n' +
117
- 'You can find a complete log in the terminal.');
118
- break;
119
- }
120
- console.warn(stripAnsi(formatted.warnings[i]));
119
+ if (i === 5) {
120
+ console.warn("There were more warnings in other files.\nYou can find a complete log in the terminal.");
121
+ break;
122
+ }
123
+ console.warn(stripAnsi(formatted.warnings[i]));
121
124
  }
122
- }
123
- // Attempt to apply hot updates or reload.
124
- if (isHotUpdate) {
125
+ }
126
+ if (isHotUpdate) {
125
127
  tryApplyUpdates(function onSuccessfulHotUpdate() {
126
- // Only dismiss it when we're sure it's a hot update.
127
- // Otherwise it would flicker right before the reload.
128
- tryDismissErrorOverlay();
128
+ tryDismissErrorOverlay();
129
129
  });
130
+ }
130
131
  }
131
- }
132
- function handleErrors(errors) {
133
- isFirstCompilation = false;
134
- hasCompileErrors = true;
135
- const formatted = formatWebpackMessages({
132
+ function handleErrors(errors) {
133
+ isFirstCompilation = false;
134
+ hasCompileErrors = true;
135
+ const formatted = formatWebpackMessages({
136
136
  warnings: [],
137
- errors,
138
- });
139
- // Only show the first error.
140
- ErrorOverlay.reportBuildError(formatted.errors[0]);
141
- // Also log them to the console.
142
- if (typeof console !== 'undefined' && typeof console.error === 'function') {
137
+ errors
138
+ });
139
+ ErrorOverlay.reportBuildError(formatted.errors[0]);
140
+ if (typeof console !== "undefined" && typeof console.error === "function") {
143
141
  for (let i = 0; i < formatted.errors.length; i++) {
144
- console.error(stripAnsi(formatted.errors[i]));
142
+ console.error(stripAnsi(formatted.errors[i]));
145
143
  }
144
+ }
146
145
  }
147
- }
148
- function tryDismissErrorOverlay() {
149
- if (!hasCompileErrors) {
146
+ function tryDismissErrorOverlay() {
147
+ if (!hasCompileErrors) {
150
148
  ErrorOverlay.dismissBuildError();
149
+ }
150
+ }
151
+ function isUpdateAvailable() {
152
+ return mostRecentCompilationHash !== __webpack_hash__;
153
+ }
154
+ function canApplyUpdates() {
155
+ return module.hot.status() === "idle";
151
156
  }
152
- }
153
- // Is there a newer version of this code available?
154
- function isUpdateAvailable() {
155
- // @ts-ignore
156
- return mostRecentCompilationHash !== __webpack_hash__;
157
- }
158
- function canApplyUpdates() {
159
- // @ts-ignore
160
- return module.hot.status() === 'idle';
161
- }
162
- function canAcceptErrors() {
163
- // NOTE: This var is injected by Webpack's DefinePlugin, and is a boolean instead of string.
164
- const hasReactRefresh = process.env.FAST_REFRESH;
165
- // @ts-ignore
166
- const status = module.hot.status();
167
- // React refresh can handle hot-reloading over errors.
168
- // However, when hot-reload status is abort or fail,
169
- // it indicates the current update cannot be applied safely,
170
- // and thus we should bail out to a forced reload for consistency.
171
- return hasReactRefresh && ['abort', 'fail'].indexOf(status) === -1;
172
- }
173
- function tryApplyUpdates(onHotUpdateSuccess) {
174
- // @ts-ignore
175
- if (!module.hot) {
157
+ function canAcceptErrors() {
158
+ const hasReactRefresh = process.env.FAST_REFRESH;
159
+ const status = module.hot.status();
160
+ return hasReactRefresh && ["abort", "fail"].indexOf(status) === -1;
161
+ }
162
+ function tryApplyUpdates(onHotUpdateSuccess) {
163
+ if (!module.hot) {
176
164
  window.location.reload();
177
165
  return;
178
- }
179
- if (!isUpdateAvailable() || !canApplyUpdates()) {
166
+ }
167
+ if (!isUpdateAvailable() || !canApplyUpdates()) {
180
168
  return;
181
- }
182
- function handleApplyUpdates(err, updatedModules) {
169
+ }
170
+ function handleApplyUpdates(err, updatedModules) {
183
171
  const haveErrors = err || hadRuntimeError;
184
- // When there is no error but updatedModules is unavailable,
185
- // it indicates a critical failure in hot-reloading,
186
- // e.g. server is not ready to serve new bundle,
187
- // and hence we need to do a forced reload.
188
172
  const needsForcedReload = !err && !updatedModules;
189
- if ((haveErrors && !canAcceptErrors()) || needsForcedReload) {
190
- window.location.reload();
173
+ if (haveErrors && !canAcceptErrors() || needsForcedReload) {
174
+ window.location.reload();
191
175
  }
192
176
  if (onHotUpdateSuccess)
193
- onHotUpdateSuccess();
194
- // While we were updating, there was a new update! Do it again.
177
+ onHotUpdateSuccess();
195
178
  if (isUpdateAvailable()) {
196
- tryApplyUpdates();
179
+ tryApplyUpdates();
197
180
  }
198
- }
199
- // @ts-ignore
200
- module.hot
201
- .check(/* autoApply */ true)
202
- .then((updatedModules) => {
181
+ }
182
+ module.hot.check(true).then((updatedModules) => {
203
183
  handleApplyUpdates(null, updatedModules);
204
- })
205
- .catch((err) => {
184
+ }).catch((err) => {
206
185
  handleApplyUpdates(err, null);
207
- });
208
- }
209
- function handleMessage(payload) {
210
- return __awaiter(this, void 0, void 0, function* () {
211
- // console.log('[payload]', payload);
186
+ });
187
+ }
188
+ function handleMessage(payload) {
189
+ return __async(this, null, function* () {
212
190
  switch (payload.type) {
213
- case MESSAGE_TYPE.hash:
214
- handleAvailableHash(payload.data);
215
- break;
216
- case MESSAGE_TYPE.stillOk:
217
- case MESSAGE_TYPE.ok:
218
- handleSuccess();
219
- break;
220
- case MESSAGE_TYPE.errors:
221
- handleErrors(payload.data);
222
- break;
223
- case MESSAGE_TYPE.warnings:
224
- handleWarnings(payload.data);
225
- break;
226
- default:
227
- // Do nothing
191
+ case MESSAGE_TYPE.hash:
192
+ handleAvailableHash(payload.data);
193
+ break;
194
+ case MESSAGE_TYPE.stillOk:
195
+ case MESSAGE_TYPE.ok:
196
+ handleSuccess();
197
+ break;
198
+ case MESSAGE_TYPE.errors:
199
+ handleErrors(payload.data);
200
+ break;
201
+ case MESSAGE_TYPE.warnings:
202
+ handleWarnings(payload.data);
203
+ break;
204
+ default:
228
205
  }
229
- });
230
- }
206
+ });
207
+ }
208
+ }
209
+ });
210
+ export default require_client();
@@ -0,0 +1,15 @@
1
+ export declare const DEFAULT_DEVTOOL = "cheap-module-source-map";
2
+ export declare const DEFAULT_OUTPUT_PATH = "dist";
3
+ export declare const MFSU_NAME = "MFSU";
4
+ export declare enum MESSAGE_TYPE {
5
+ ok = "ok",
6
+ warnings = "warnings",
7
+ errors = "errors",
8
+ hash = "hash",
9
+ stillOk = "still-ok",
10
+ invalid = "invalid"
11
+ }
12
+ export declare const DEFAULT_BROWSER_TARGETS: {
13
+ chrome: number;
14
+ };
15
+ export declare const DEFAULT_ESBUILD_TARGET_KEYS: string[];
@@ -1,21 +1,30 @@
1
- export const DEFAULT_DEVTOOL = 'cheap-module-source-map';
2
- export const DEFAULT_OUTPUT_PATH = 'dist';
3
- export const MFSU_NAME = 'MFSU';
4
- export var MESSAGE_TYPE;
5
- (function (MESSAGE_TYPE) {
6
- MESSAGE_TYPE["ok"] = "ok";
7
- MESSAGE_TYPE["warnings"] = "warnings";
8
- MESSAGE_TYPE["errors"] = "errors";
9
- MESSAGE_TYPE["hash"] = "hash";
10
- MESSAGE_TYPE["stillOk"] = "still-ok";
11
- MESSAGE_TYPE["invalid"] = "invalid";
12
- })(MESSAGE_TYPE || (MESSAGE_TYPE = {}));
13
- export const DEFAULT_BROWSER_TARGETS = {
14
- chrome: 80,
1
+ // constants.ts
2
+ var DEFAULT_DEVTOOL = "cheap-module-source-map";
3
+ var DEFAULT_OUTPUT_PATH = "dist";
4
+ var MFSU_NAME = "MFSU";
5
+ var MESSAGE_TYPE = /* @__PURE__ */ ((MESSAGE_TYPE2) => {
6
+ MESSAGE_TYPE2["ok"] = "ok";
7
+ MESSAGE_TYPE2["warnings"] = "warnings";
8
+ MESSAGE_TYPE2["errors"] = "errors";
9
+ MESSAGE_TYPE2["hash"] = "hash";
10
+ MESSAGE_TYPE2["stillOk"] = "still-ok";
11
+ MESSAGE_TYPE2["invalid"] = "invalid";
12
+ return MESSAGE_TYPE2;
13
+ })(MESSAGE_TYPE || {});
14
+ var DEFAULT_BROWSER_TARGETS = {
15
+ chrome: 80
15
16
  };
16
- export const DEFAULT_ESBUILD_TARGET_KEYS = [
17
- 'chrome',
18
- 'firefox',
19
- 'edge',
20
- 'safari',
17
+ var DEFAULT_ESBUILD_TARGET_KEYS = [
18
+ "chrome",
19
+ "firefox",
20
+ "edge",
21
+ "safari"
21
22
  ];
23
+ export {
24
+ DEFAULT_BROWSER_TARGETS,
25
+ DEFAULT_DEVTOOL,
26
+ DEFAULT_ESBUILD_TARGET_KEYS,
27
+ DEFAULT_OUTPUT_PATH,
28
+ MESSAGE_TYPE,
29
+ MFSU_NAME
30
+ };
@@ -0,0 +1,12 @@
1
+ export declare function formatMessage(message: string | {
2
+ message: string;
3
+ } | {
4
+ message: string;
5
+ }[]): string;
6
+ export declare function formatWebpackMessages(json: {
7
+ errors: string[];
8
+ warnings: string[];
9
+ }): {
10
+ errors: string[];
11
+ warnings: string[];
12
+ };
@@ -1,92 +1,74 @@
1
- import stripAnsi from '@umijs/utils/compiled/strip-ansi';
2
- const friendlySyntaxErrorLabel = 'Syntax error:';
1
+ // formatWebpackMessages.ts
2
+ import stripAnsi from "@umijs/utils/compiled/strip-ansi";
3
+ var friendlySyntaxErrorLabel = "Syntax error:";
3
4
  function isLikelyASyntaxError(message) {
4
- return stripAnsi(message).indexOf(friendlySyntaxErrorLabel) !== -1;
5
+ return stripAnsi(message).indexOf(friendlySyntaxErrorLabel) !== -1;
5
6
  }
6
- export function formatMessage(message) {
7
- let lines = [];
8
- if (typeof message === 'string') {
9
- lines = message.split('\n');
10
- }
11
- else if ('message' in message) {
12
- lines = message['message'].split('\n');
13
- }
14
- else if (Array.isArray(message)) {
15
- message.forEach((message) => {
16
- if ('message' in message) {
17
- lines = message['message'].split('\n');
18
- }
19
- });
20
- }
21
- // Strip webpack-added headers off errors/warnings
22
- // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
23
- lines = lines.filter((line) => !/Module [A-z ]+\(from/.test(line));
24
- // Transform parsing error into syntax error
25
- // TODO: move this to our ESLint formatter?
26
- lines = lines.map((line) => {
27
- const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line);
28
- if (!parsingError) {
29
- return line;
30
- }
31
- const [, errorLine, errorColumn, errorMessage] = parsingError;
32
- return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`;
7
+ function formatMessage(message) {
8
+ let lines = [];
9
+ if (typeof message === "string") {
10
+ lines = message.split("\n");
11
+ } else if ("message" in message) {
12
+ lines = message["message"].split("\n");
13
+ } else if (Array.isArray(message)) {
14
+ message.forEach((message2) => {
15
+ if ("message" in message2) {
16
+ lines = message2["message"].split("\n");
17
+ }
33
18
  });
34
- message = lines.join('\n');
35
- // Smoosh syntax errors (commonly found in CSS)
36
- message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, `${friendlySyntaxErrorLabel} $3 ($1:$2)\n`);
37
- // Clean up export errors
38
- message = message.replace(/^.*export '(.+?)' was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$2'.`);
39
- message = message.replace(/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$2' does not contain a default export (imported as '$1').`);
40
- message = message.replace(/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`);
41
- lines = message.split('\n');
42
- // Remove leading newline
43
- if (lines.length > 2 && lines[1].trim() === '') {
44
- lines.splice(1, 1);
45
- }
46
- // Clean up file name
47
- lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1');
48
- // Cleans up verbose "module not found" messages for files and packages.
49
- if (lines[1] && lines[1].indexOf('Module not found: ') === 0) {
50
- lines = [
51
- lines[0],
52
- lines[1]
53
- .replace('Error: ', '')
54
- .replace('Module not found: Cannot find file:', 'Cannot find file:'),
55
- ];
19
+ }
20
+ lines = lines.filter((line) => !/Module [A-z ]+\(from/.test(line));
21
+ lines = lines.map((line) => {
22
+ const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line);
23
+ if (!parsingError) {
24
+ return line;
56
25
  }
57
- // Add helpful message for users trying to use Sass for the first time
58
- if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {
59
- lines[1] = 'To import Sass files, you first need to install sass.\n';
60
- lines[1] +=
61
- 'Run `npm install sass` or `yarn add sass` inside your workspace.';
62
- }
63
- message = lines.join('\n');
64
- // Internal stacks are generally useless so we strip them... with the
65
- // exception of stacks containing `webpack:` because they're normally
66
- // from user code generated by webpack. For more information see
67
- // https://github.com/facebook/create-react-app/pull/1050
68
- message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y
69
- message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, ''); // at <anonymous>
70
- lines = message.split('\n');
71
- // Remove duplicated newlines
72
- lines = lines.filter((line, index, arr) => index === 0 ||
73
- line.trim() !== '' ||
74
- line.trim() !== arr[index - 1].trim());
75
- // Reassemble the message
76
- message = lines.join('\n');
77
- return message.trim();
26
+ const [, errorLine, errorColumn, errorMessage] = parsingError;
27
+ return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`;
28
+ });
29
+ message = lines.join("\n");
30
+ message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, `${friendlySyntaxErrorLabel} $3 ($1:$2)
31
+ `);
32
+ message = message.replace(/^.*export '(.+?)' was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$2'.`);
33
+ message = message.replace(/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$2' does not contain a default export (imported as '$1').`);
34
+ message = message.replace(/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`);
35
+ lines = message.split("\n");
36
+ if (lines.length > 2 && lines[1].trim() === "") {
37
+ lines.splice(1, 1);
38
+ }
39
+ lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, "$1");
40
+ if (lines[1] && lines[1].indexOf("Module not found: ") === 0) {
41
+ lines = [
42
+ lines[0],
43
+ lines[1].replace("Error: ", "").replace("Module not found: Cannot find file:", "Cannot find file:")
44
+ ];
45
+ }
46
+ if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {
47
+ lines[1] = "To import Sass files, you first need to install sass.\n";
48
+ lines[1] += "Run `npm install sass` or `yarn add sass` inside your workspace.";
49
+ }
50
+ message = lines.join("\n");
51
+ message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, "");
52
+ message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, "");
53
+ lines = message.split("\n");
54
+ lines = lines.filter((line, index, arr) => index === 0 || line.trim() !== "" || line.trim() !== arr[index - 1].trim());
55
+ message = lines.join("\n");
56
+ return message.trim();
78
57
  }
79
- export function formatWebpackMessages(json) {
80
- const formattedErrors = json.errors.map(function (message) {
81
- return formatMessage(message);
82
- });
83
- const formattedWarnings = json.warnings.map(function (message) {
84
- return formatMessage(message);
85
- });
86
- const result = { errors: formattedErrors, warnings: formattedWarnings };
87
- if (result.errors.some(isLikelyASyntaxError)) {
88
- // If there are any syntax errors, show just them.
89
- result.errors = result.errors.filter(isLikelyASyntaxError);
90
- }
91
- return result;
58
+ function formatWebpackMessages(json) {
59
+ const formattedErrors = json.errors.map(function(message) {
60
+ return formatMessage(message);
61
+ });
62
+ const formattedWarnings = json.warnings.map(function(message) {
63
+ return formatMessage(message);
64
+ });
65
+ const result = { errors: formattedErrors, warnings: formattedWarnings };
66
+ if (result.errors.some(isLikelyASyntaxError)) {
67
+ result.errors = result.errors.filter(isLikelyASyntaxError);
68
+ }
69
+ return result;
92
70
  }
71
+ export {
72
+ formatMessage,
73
+ formatWebpackMessages
74
+ };