UNPKG

2 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5"use strict";
6
7const WebpackError = require("./WebpackError");
8
9/** @typedef {import("./Module")} Module */
10
11class ModuleParseError extends WebpackError {
12 /**
13 * @param {Module} module the errored module
14 * @param {string} source source code
15 * @param {Error&any} err the parse error
16 * @param {string[]} loaders the loaders used
17 */
18 constructor(module, source, err, loaders) {
19 let message = "Module parse failed: " + err.message;
20 let loc = undefined;
21 if (loaders.length >= 1) {
22 message += `\nFile was processed with these loaders:${loaders
23 .map(loader => `\n * ${loader}`)
24 .join("")}`;
25 message +=
26 "\nYou may need an additional loader to handle the result of these loaders.";
27 } else {
28 message +=
29 "\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders";
30 }
31 if (
32 err.loc &&
33 typeof err.loc === "object" &&
34 typeof err.loc.line === "number"
35 ) {
36 var lineNumber = err.loc.line;
37 if (/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) {
38 // binary file
39 message += "\n(Source code omitted for this binary file)";
40 } else {
41 const sourceLines = source.split(/\r?\n/);
42 const start = Math.max(0, lineNumber - 3);
43 const linesBefore = sourceLines.slice(start, lineNumber - 1);
44 const theLine = sourceLines[lineNumber - 1];
45 const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2);
46 message +=
47 linesBefore.map(l => `\n| ${l}`).join("") +
48 `\n> ${theLine}` +
49 linesAfter.map(l => `\n| ${l}`).join("");
50 }
51 loc = err.loc;
52 } else {
53 message += "\n" + err.stack;
54 }
55
56 super(message);
57
58 this.name = "ModuleParseError";
59 this.module = module;
60 this.loc = loc;
61 this.error = err;
62
63 Error.captureStackTrace(this, this.constructor);
64 }
65}
66
67module.exports = ModuleParseError;