error.ts 1023 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { Context } from 'cordis'
  2. import type { BuildFailure } from 'esbuild'
  3. import { codeFrameColumns } from '@babel/code-frame'
  4. import { readFileSync } from 'node:fs'
  5. function isBuildFailure(e: any): e is BuildFailure {
  6. return Array.isArray(e?.errors) && e.errors.every((error: any) => error.text)
  7. }
  8. /** Log HMR build failures with code frames when source locations are available. */
  9. export function handleError(ctx: Context, e: any) {
  10. if (!isBuildFailure(e)) {
  11. ctx.logger.warn(e)
  12. return
  13. }
  14. for (const error of e.errors) {
  15. if (!error.location) {
  16. ctx.logger.warn(error.text)
  17. continue
  18. }
  19. try {
  20. const { file, line, column } = error.location
  21. const source = readFileSync(file, 'utf8')
  22. const formatted = codeFrameColumns(source, {
  23. start: { line, column },
  24. }, {
  25. highlightCode: true,
  26. message: error.text,
  27. })
  28. ctx.logger.warn(`File: ${file}:${line}:${column}\n` + formatted)
  29. } catch (e) {
  30. ctx.logger.warn(e)
  31. }
  32. }
  33. }