-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.ts
More file actions
70 lines (56 loc) · 1.69 KB
/
dev.ts
File metadata and controls
70 lines (56 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { watch } from 'fs';
import { join } from 'path';
let bundleCache: string | null = null;
async function bundle(): Promise<string> {
const result = await Bun.build({
entrypoints: ['./src/main.ts'],
minify: false,
sourcemap: 'inline',
});
if (!result.success) {
console.error('Build failed:', result.logs);
return '';
}
return await result.outputs[0].text();
}
// Initial bundle
bundleCache = await bundle();
// Watch for changes
watch('./src', { recursive: true }, async (event, filename) => {
console.log(`File changed: ${filename}, rebuilding...`);
bundleCache = await bundle();
});
const server = Bun.serve({
port: 3000,
async fetch(req) {
const url = new URL(req.url);
let path = url.pathname;
if (path === '/') {
path = '/index.html';
}
// Serve bundled JS
if (path === '/main.ts' || path === '/main.js') {
return new Response(bundleCache, {
headers: { 'Content-Type': 'application/javascript' },
});
}
// Serve static files from src
const filePath = `./src${path}`;
const file = Bun.file(filePath);
if (await file.exists()) {
const contentType = getContentType(path);
return new Response(file, {
headers: { 'Content-Type': contentType },
});
}
return new Response('Not Found', { status: 404 });
},
});
function getContentType(path: string): string {
if (path.endsWith('.html')) return 'text/html';
if (path.endsWith('.css')) return 'text/css';
if (path.endsWith('.js')) return 'application/javascript';
if (path.endsWith('.json')) return 'application/json';
return 'text/plain';
}
console.log(`Dev server running at http://localhost:${server.port}`);