Skip to content

Instantly share code, notes, and snippets.

@arvinall
Created October 15, 2025 16:25
Show Gist options
  • Save arvinall/aabdc623162f4ebfdcd57eb1abe0c5e3 to your computer and use it in GitHub Desktop.
Save arvinall/aabdc623162f4ebfdcd57eb1abe0c5e3 to your computer and use it in GitHub Desktop.
Bun script to serve a simple front library playground

Library Playground

Save file in one of your paths directories then rename lpg.js to-> lpg (remove .js ext)

Then make it executable via: chmod +x lpg

Examples

~/projects/lib1> lpg # serve namespace reference to .../lib1/lib/index.js at localhost:3000 as globalThis.lib1

~/projects/lib1> lpg lib # serve namespace reference to .../lib1/lib/index.js at localhost:3000 as globalThis.lib1

~/projects/lib2> lpg src # serve namespace reference to .../lib2/src/index.js at localhost:3000 as globalThis.lib2

~/projects> lpg lib1/lib # serve namespace reference to .../lib1/lib/index.js at localhost:3000 as globalThis.lib1

~/projects> lpg lib2/src # serve namespace reference to .../lib2/src/index.js at localhost:3000 as globalThis.lib2
#!/usr/bin/env bun
import { serve, file } from 'bun'
import { resolve, join, dirname, basename } from 'node:path'
import { cwd, argv } from 'node:process'
import { writeFile, constants, access, stat, rm } from 'node:fs/promises'
var libPath = resolve(cwd(), argv[2]?.trim?.() || 'lib')
if (libPath.endsWith(join('lib', 'lib'))) (
(libPath = resolve(libPath, '..'))
)
var libDirName = basename(libPath)
var pkgPath = dirname(libPath)
var pkgDirName = basename(pkgPath)
var pkgName = (await import(join(pkgPath, 'package.json'))).default.name
var playgroundHtml = `<!DOCTYPE html>
<script type="module">
import * as api from '/${libDirName}/index.js'
globalThis.${pkgDirName} = api
document.title = '${pkgName} Library'
Object.assign(document.body.style, { background: '#242424', color: '#dbdbdb' })
</script>
`
var playgroundHtmlPath = join(pkgPath, 'playground.html')
await writeFile(playgroundHtmlPath, playgroundHtml)
var server = serve({
async fetch (req) {
var
filePath = join(pkgPath, (new URL(req.url)).pathname)
,blob
try {
await access(filePath, constants.R_OK)
if (!((await stat(filePath)).isDirectory())) (
blob = file(filePath)
)
else (
(filePath = join(filePath, 'index.html'))
,await access(filePath, constants.R_OK)
,(blob = file(filePath))
)
} catch (error) {
blob = file(playgroundHtmlPath)
}
return new Response(blob)
}
})
globalThis.process.once('SIGINT', () => (
server.stop()
,rm(playgroundHtmlPath)
))
console.log(` Playground served (${pkgName})\n at ${server.url.origin}\n as globalThis.${pkgDirName}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment