Skip to content

Commit

Permalink
feat(hmr): add syntax output for build errors (#1083)
Browse files Browse the repository at this point in the history
Co-authored-by: Shigma <[email protected]>
  • Loading branch information
HuanLinOTO and shigma authored May 6, 2023
1 parent 5d5ba30 commit 2147314
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
3 changes: 3 additions & 0 deletions plugins/hmr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,13 @@
"koishi": "^4.12.7"
},
"devDependencies": {
"@types/babel__code-frame": "^7.0.3",
"@types/throttle-debounce": "^2.1.0",
"esbuild": "^0.17.18",
"koishi": "^4.12.7"
},
"dependencies": {
"@babel/code-frame": "^7.21.4",
"chokidar": "^3.5.3",
"throttle-debounce": "^3.0.1"
}
Expand Down
37 changes: 37 additions & 0 deletions plugins/hmr/src/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Logger } from 'koishi'
import { BuildFailure } from 'esbuild'
import { codeFrameColumns } from '@babel/code-frame'
import { readFileSync } from 'fs'

const logger = new Logger('watch')

function isBuildFailure(e: any): e is BuildFailure {
return Array.isArray(e?.errors) && e.errors.every((error: any) => error.text)
}

export function handleError(e: any) {
if (!isBuildFailure(e)) {
logger.warn(e)
return
}

for (const error of e.errors) {
if (!error.location) {
logger.warn(error.text)
continue
}
try {
const { file, line, column } = error.location
const source = readFileSync(file, 'utf8')
const formatted = codeFrameColumns(source, {
start: { line, column },
}, {
highlightCode: true,
message: error.text,
})
logger.warn(`File: ${file}:${line}:${column}\n` + formatted)
} catch (e) {
logger.warn(e)
}
}
}
5 changes: 3 additions & 2 deletions plugins/hmr/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FSWatcher, watch, WatchOptions } from 'chokidar'
import { relative, resolve } from 'path'
import { debounce } from 'throttle-debounce'
import { Loader, unwrapExports } from '@koishijs/loader'
import { handleError } from './error'

declare module 'koishi' {
interface Context {
Expand Down Expand Up @@ -259,8 +260,8 @@ class Watcher {
for (const [, { filename }] of reloads) {
attempts[filename] = unwrapExports(require(filename))
}
} catch (err) {
logger.warn(err)
} catch (e) {
handleError(e)
return rollback()
}

Expand Down

0 comments on commit 2147314

Please sign in to comment.