Skip to content

Commit 5d4df77

Browse files
aymuos15ampcode-com
andcommitted
Add Bun dev server
Amp-Thread-ID: https://ampcode.com/threads/T-019de8e8-c3cf-779f-ba09-a1a89c43ac65 Co-authored-by: Amp <amp@ampcode.com>
1 parent 40d5850 commit 5d4df77

3 files changed

Lines changed: 51 additions & 2 deletions

File tree

dev-server.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { extname, resolve } from 'node:path';
2+
3+
const port = Number(process.env.PORT || 3000);
4+
const rootDir = resolve(import.meta.dir, 'src');
5+
6+
function resolvePath(pathname) {
7+
const relativePath = pathname === '/' ? 'index.html' : pathname.slice(1);
8+
const targetPath = resolve(rootDir, relativePath);
9+
10+
if (targetPath !== rootDir && !targetPath.startsWith(`${rootDir}/`)) {
11+
return null;
12+
}
13+
14+
return targetPath;
15+
}
16+
17+
const server = Bun.serve({
18+
port,
19+
development: true,
20+
async fetch(req) {
21+
const url = new URL(req.url);
22+
const pathname = decodeURIComponent(url.pathname);
23+
const targetPath = resolvePath(pathname);
24+
25+
if (!targetPath) {
26+
return new Response('Not found', { status: 404 });
27+
}
28+
29+
const file = Bun.file(targetPath);
30+
31+
if (await file.exists()) {
32+
return new Response(file);
33+
}
34+
35+
if (!extname(pathname)) {
36+
const fallback = Bun.file(resolve(rootDir, 'index.html'));
37+
return new Response(fallback);
38+
}
39+
40+
return new Response('Not found', { status: 404 });
41+
}
42+
});
43+
44+
console.log(`Dev server running at http://localhost:${server.port}`);

eslint.config.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ export default [
66
ecmaVersion: 2022,
77
sourceType: 'module',
88
globals: {
9+
Bun: 'readonly',
10+
URL: 'readonly',
11+
Response: 'readonly',
12+
process: 'readonly',
913
window: 'readonly',
1014
document: 'readonly',
1115
console: 'readonly',

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
"type": "module",
66
"packageManager": "bun@1.2.22",
77
"scripts": {
8+
"dev": "bun run dev-server.js",
89
"lint": "bun run lint:js && bun run lint:css && bun run lint:html",
9-
"lint:js": "eslint \"src/js/**/*.js\" \"src/microblogs/**/*.js\"",
10+
"lint:js": "eslint dev-server.js \"src/js/**/*.js\" \"src/microblogs/**/*.js\"",
1011
"lint:css": "stylelint \"src/styles/**/*.css\"",
1112
"lint:html": "htmlhint src/index.html",
12-
"lint:fix": "eslint \"src/js/**/*.js\" \"src/microblogs/**/*.js\" --fix && stylelint \"src/styles/**/*.css\" --fix",
13+
"lint:fix": "eslint dev-server.js \"src/js/**/*.js\" \"src/microblogs/**/*.js\" --fix && stylelint \"src/styles/**/*.css\" --fix",
1314
"prepare": "husky"
1415
},
1516
"lint-staged": {

0 commit comments

Comments
 (0)