CompileErrorTrace.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const ansiHTML = require('ansi-html-community');
  2. const entities = require('html-entities');
  3. const theme = require('../theme.js');
  4. const utils = require('../utils.js');
  5. ansiHTML.setColors(theme);
  6. /**
  7. * @typedef {Object} CompileErrorTraceProps
  8. * @property {string} errorMessage
  9. */
  10. /**
  11. * A formatter that turns Webpack compile error messages into highlighted HTML source traces.
  12. * @param {Document} document
  13. * @param {HTMLElement} root
  14. * @param {CompileErrorTraceProps} props
  15. * @returns {void}
  16. */
  17. function CompileErrorTrace(document, root, props) {
  18. const errorParts = props.errorMessage.split('\n');
  19. if (errorParts.length) {
  20. if (errorParts[0]) {
  21. errorParts[0] = utils.formatFilename(errorParts[0]);
  22. }
  23. const errorMessage = errorParts.splice(1, 1)[0];
  24. if (errorMessage) {
  25. // Strip filename from the error message
  26. errorParts.unshift(errorMessage.replace(/^(.*:)\s.*:(\s.*)$/, '$1$2'));
  27. }
  28. }
  29. const stackContainer = document.createElement('pre');
  30. stackContainer.innerHTML = entities.decode(
  31. ansiHTML(entities.encode(errorParts.join('\n'), { level: 'html5', mode: 'nonAscii' })),
  32. { level: 'html5' }
  33. );
  34. stackContainer.style.fontFamily = [
  35. '"Operator Mono SSm"',
  36. '"Operator Mono"',
  37. '"Fira Code Retina"',
  38. '"Fira Code"',
  39. '"FiraCode-Retina"',
  40. '"Andale Mono"',
  41. '"Lucida Console"',
  42. 'Menlo',
  43. 'Consolas',
  44. 'Monaco',
  45. 'monospace',
  46. ].join(', ');
  47. stackContainer.style.margin = '0';
  48. stackContainer.style.whiteSpace = 'pre-wrap';
  49. root.appendChild(stackContainer);
  50. }
  51. module.exports = CompileErrorTrace;