ModuleParseError.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const WebpackError = require("./WebpackError");
  7. /** @typedef {import("./Module")} Module */
  8. class ModuleParseError extends WebpackError {
  9. /**
  10. * @param {Module} module the errored module
  11. * @param {string} source source code
  12. * @param {Error&any} err the parse error
  13. */
  14. constructor(module, source, err) {
  15. let message = "Module parse failed: " + err.message;
  16. let loc = undefined;
  17. message += "\nYou may need an appropriate loader to handle this file type.";
  18. if (
  19. err.loc &&
  20. typeof err.loc === "object" &&
  21. typeof err.loc.line === "number"
  22. ) {
  23. var lineNumber = err.loc.line;
  24. if (/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) {
  25. // binary file
  26. message += "\n(Source code omitted for this binary file)";
  27. } else {
  28. const sourceLines = source.split("\n");
  29. const start = Math.max(0, lineNumber - 3);
  30. const linesBefore = sourceLines.slice(start, lineNumber - 1);
  31. const theLine = sourceLines[lineNumber - 1];
  32. const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2);
  33. message +=
  34. linesBefore.map(l => `\n| ${l}`).join("") +
  35. `\n> ${theLine}` +
  36. linesAfter.map(l => `\n| ${l}`).join("");
  37. }
  38. loc = err.loc;
  39. } else {
  40. message += "\n" + err.stack;
  41. }
  42. super(message);
  43. this.name = "ModuleParseError";
  44. this.module = module;
  45. this.loc = loc;
  46. this.error = err;
  47. Error.captureStackTrace(this, this.constructor);
  48. }
  49. }
  50. module.exports = ModuleParseError;