Files
seastem-electronjs/compile.ts
T
imbytecat e28fe9dc7b perf(compile): 启用 bytecode + minify + inline sourcemap
- Bun 官方 bytecode caching:中型应用 startup ~2x(docs.bun.sh/docs/bundler/bytecode)
- minify:减小 bytecode 体积,二进制仅 +2MB sourcemap
- sourcemap inline:嵌入二进制,保证错误堆栈可读,并在 compile.ts 清理 bundler 残留的 *.js.map
2026-04-25 14:05:35 +08:00

71 lines
2.0 KiB
TypeScript

import { mkdir, rm } from 'node:fs/promises'
import { parseArgs } from 'node:util'
const ENTRYPOINT = 'bin.ts'
const OUTDIR = 'out'
const SUPPORTED_TARGETS: readonly Bun.Build.CompileTarget[] = [
'bun-windows-x64',
'bun-darwin-arm64',
'bun-darwin-x64',
'bun-linux-x64',
'bun-linux-arm64',
]
const isSupportedTarget = (value: string): value is Bun.Build.CompileTarget =>
(SUPPORTED_TARGETS as readonly string[]).includes(value)
const { values } = parseArgs({
options: { target: { type: 'string' } },
strict: true,
allowPositionals: false,
})
const resolveTarget = (): Bun.Build.CompileTarget => {
if (values.target !== undefined) {
if (!isSupportedTarget(values.target)) {
throw new Error(`Invalid target: ${values.target}\nAllowed: ${SUPPORTED_TARGETS.join(', ')}`)
}
return values.target
}
const os = process.platform === 'win32' ? 'windows' : process.platform
const candidate = `bun-${os}-${process.arch}`
if (!isSupportedTarget(candidate)) {
throw new Error(`Unsupported host: ${process.platform}-${process.arch}`)
}
return candidate
}
const main = async () => {
const target = resolveTarget()
const suffix = target.replace('bun-', '')
const outfile = `server-${suffix}`
await mkdir(OUTDIR, { recursive: true })
await Promise.all([rm(`${OUTDIR}/${outfile}`, { force: true }), rm(`${OUTDIR}/${outfile}.exe`, { force: true })])
const result = await Bun.build({
entrypoints: [ENTRYPOINT],
outdir: OUTDIR,
compile: { outfile, target },
minify: true,
bytecode: true,
sourcemap: 'inline',
})
if (!result.success) {
throw new Error(result.logs.map(String).join('\n'))
}
// Bun bundler still writes *.js.map next to the binary even with inline sourcemap.
await rm(`${OUTDIR}/${ENTRYPOINT.replace(/\.ts$/, '')}.js.map`, { force: true })
console.log(`${target}${OUTDIR}/${outfile}`)
}
main().catch((err) => {
console.error('❌', err instanceof Error ? err.message : err)
process.exit(1)
})