-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdev.js
More file actions
101 lines (92 loc) · 2.61 KB
/
dev.js
File metadata and controls
101 lines (92 loc) · 2.61 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import express from "express";
import chokidar from "chokidar";
import { exec } from "child_process";
import path from "path";
import livereload from "livereload";
import connectLivereload from "connect-livereload";
import open from "open";
import net from "net";
import { fileURLToPath } from "url";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const PORT = 3000;
const MAX_PORT = 3010; // Try ports between 3000 and 3010
const DIST_DIR = path.join(__dirname, "dist");
// Check if a port is in use
function isPortInUse(port) {
return new Promise((resolve) => {
const server = net
.createServer()
.once("error", () => resolve(true))
.once("listening", () => {
server.close();
resolve(false);
})
.listen(port);
});
}
// Find an available port
async function findAvailablePort(startPort, maxPort) {
let port = startPort;
while (port <= maxPort) {
const inUse = await isPortInUse(port);
if (!inUse) {
return port;
}
port++;
}
throw new Error(
`No available ports found between ${startPort} and ${maxPort}`
);
}
// Enable live reload
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(DIST_DIR);
app.use(connectLivereload());
// Serve static files from the dist directory
app.use(express.static(DIST_DIR));
// Watch for changes in the source files
const watcher = chokidar.watch(
["posts", "pages", "ui", "static", "build.js", "builders", "utils"],
{
ignored: /(^|[\/\\])\../, // Ignore dotfiles
persistent: true,
}
);
// Rebuild the site on file changes
watcher.on("change", (filePath) => {
console.log(`File changed: ${filePath}`);
console.log("Rebuilding site...");
exec("node build.js", (err, stdout, stderr) => {
if (err) {
console.error(`Error during build: ${stderr}`);
} else {
console.log(stdout);
liveReloadServer.refresh("/");
}
});
});
// Start the development server
(async () => {
console.log("Building site...");
exec("node build.js", async (err, stdout, stderr) => {
if (err) {
console.error(`Error during initial build: ${stderr}`);
} else {
console.log(stdout);
try {
const availablePort = await findAvailablePort(PORT, MAX_PORT);
app.listen(availablePort, async () => {
console.log(
`Dev server running at http://localhost:${availablePort}`
);
await open(`http://localhost:${availablePort}`);
});
} catch (error) {
console.error(error.message);
}
}
});
})();