formatLessError.js 2.1 KB

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