include import when transpiling frontend files

This commit is contained in:
Chris Wanstrath 2025-12-14 15:53:34 -08:00
parent 192b0cf88d
commit 1df3f0760e

View File

@ -8,6 +8,8 @@ export function css(strings: TemplateStringsArray, ...values: any[]) {
}} /> }} />
} }
const transpiler = new Bun.Transpiler({ loader: 'tsx' })
// template literal tag for inline JS. transpiles and returns a <script> tag // template literal tag for inline JS. transpiles and returns a <script> tag
export function js(strings: TemplateStringsArray, ...values: any[]) { export function js(strings: TemplateStringsArray, ...values: any[]) {
return <script dangerouslySetInnerHTML={{ return <script dangerouslySetInnerHTML={{
@ -137,21 +139,25 @@ export function weightedRand(): number {
return numbers[numbers.length - 1]! return numbers[numbers.length - 1]!
} }
const transpiler = new Bun.Transpiler({ loader: 'tsx' })
const transpileCache: Record<string, string> = {} const transpileCache: Record<string, string> = {}
// Transpile the frontend *.ts file at `path` to JavaScript. // transpile frontend ts to js
export async function transpile(path: string): Promise<string> { export async function transpile(path: string): Promise<string> {
const { mtime } = await stat(path) const { mtime } = await stat(path)
const key = `${path}?${mtime}` const key = `${path}?${mtime}`
let cached = transpileCache[key] let cached = transpileCache[key]
if (!cached) { if (!cached) {
const code = await Bun.file(path).text() const result = await Bun.build({
cached = transpiler.transformSync(code) entrypoints: [path],
cached = cached.replaceAll(/\bjsxDEV_?\w*\(/g, "jsx(") format: 'esm',
cached = cached.replaceAll(/\bFragment_?\w*,/g, "Fragment,") minify: false,
sourcemap: 'none',
})
if (!result.outputs[0]) throw new Error(`Failed to build ${path}`)
cached = await result.outputs[0].text()
transpileCache[key] = cached transpileCache[key] = cached
} }