formatLessError.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. const os = require('os');
  3. /**
  4. * Tries to get an excerpt of the file where the error happened.
  5. * Uses err.line and err.column.
  6. *
  7. * Returns an empty string if the excerpt could not be retrieved.
  8. *
  9. * @param {LessError} err
  10. * @returns {Array<string>}
  11. */
  12. function getFileExcerptIfPossible(lessErr) {
  13. try {
  14. const excerpt = lessErr.extract.slice(0, 2);
  15. const column = Math.max(lessErr.column - 1, 0);
  16. if (typeof excerpt[0] === 'undefined') {
  17. excerpt.shift();
  18. }
  19. excerpt.push(`${new Array(column).join(' ')}^`);
  20. return excerpt;
  21. } catch (unexpectedErr) {
  22. // If anything goes wrong here, we don't want any errors to be reported to the user
  23. return [];
  24. }
  25. }
  26. /**
  27. * Beautifies the error message from Less.
  28. *
  29. * @param {LessError} lessErr
  30. * @param {string} lessErr.type - e.g. 'Name'
  31. * @param {string} lessErr.message - e.g. '.undefined-mixin is undefined'
  32. * @param {string} lessErr.filename - e.g. '/path/to/style.less'
  33. * @param {number} lessErr.index - e.g. 352
  34. * @param {number} lessErr.line - e.g. 31
  35. * @param {number} lessErr.callLine - e.g. NaN
  36. * @param {string} lessErr.callExtract - e.g. undefined
  37. * @param {number} lessErr.column - e.g. 6
  38. * @param {Array<string>} lessErr.extract - e.g. [' .my-style {', ' .undefined-mixin;', ' display: block;']
  39. * @returns {LessError}
  40. */
  41. function formatLessError(err) {
  42. /* eslint-disable no-param-reassign */
  43. const msg = err.message; // Instruct webpack to hide the JS stack from the console
  44. // Usually you're only interested in the SASS stack in this case.
  45. err.hideStack = true;
  46. err.message = [os.EOL, ...getFileExcerptIfPossible(err), msg.charAt(0).toUpperCase() + msg.slice(1), ` in ${err.filename} (line ${err.line}, column ${err.column})`].join(os.EOL);
  47. return err;
  48. }
  49. /* eslint-enable no-param-reassign */
  50. module.exports = formatLessError;