Skip to content

Commit b99547b

Browse files
authored
fix: add code location and codeframe for rollup errors (#406)
1 parent 6bfbb22 commit b99547b

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

src/build.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import { promises as fsp } from 'fs'
2-
import { relative, resolve, join, dirname } from 'pathe'
2+
import { relative, resolve, join, dirname, isAbsolute } from 'pathe'
33
import * as rollup from 'rollup'
44
import fse from 'fs-extra'
55
import { defu } from 'defu'
66
import { watch } from 'chokidar'
77
import { debounce } from 'perfect-debounce'
88
import type { TSConfig } from 'pkg-types'
9+
import type { RollupError } from 'rollup'
10+
import type { OnResolveResult, PartialMessage } from 'esbuild'
911
import { printFSTree } from './utils/tree'
1012
import { getRollupConfig, RollupConfig } from './rollup/config'
1113
import { prettyPath, writeFile, isDirectory } from './utils'
@@ -138,7 +140,7 @@ async function _build (nitro: Nitro, rollupConfig: RollupConfig) {
138140

139141
nitro.logger.start('Building server...')
140142
const build = await rollup.rollup(rollupConfig).catch((error) => {
141-
nitro.logger.error('Rollup error: ' + error.message)
143+
nitro.logger.error(formatRollupError(error))
142144
throw error
143145
})
144146

@@ -204,7 +206,7 @@ function startRollupWatcher (nitro: Nitro, rollupConfig: RollupConfig) {
204206

205207
// Encountered an error while bundling
206208
case 'ERROR':
207-
nitro.logger.error('Rollup error: ', event.error)
209+
nitro.logger.error(formatRollupError(event.error))
208210
}
209211
})
210212
return watcher
@@ -240,3 +242,21 @@ async function _watch (nitro: Nitro, rollupConfig: RollupConfig) {
240242

241243
await reload()
242244
}
245+
246+
function formatRollupError (_error: RollupError | OnResolveResult) {
247+
try {
248+
const logs: string[] = []
249+
for (const error of ('errors' in _error ? _error.errors : [_error as RollupError])) {
250+
const id = error.id || (_error as RollupError).id
251+
let path = isAbsolute(id) ? relative(process.cwd(), id) : id
252+
const location = (error as RollupError).loc || (error as PartialMessage).location
253+
if (location) {
254+
path += `:${location.line}:${location.column}`
255+
}
256+
logs.push(`Rollup error while processing \`${path}\`` + '\n\n' + ((error as PartialMessage).text || (error as RollupError).frame))
257+
}
258+
return logs.join('\n\n')
259+
} catch {
260+
return _error?.toString()
261+
}
262+
}

0 commit comments

Comments
 (0)