-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdev-server.js
52 lines (49 loc) · 2.08 KB
/
dev-server.js
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
import { execSync } from "child_process";
import { readFileSync, readdirSync, watch } from "fs";
import chalk from "chalk";
import path from "path";
import consola from "consola";
console.clear()
let isCompiling = false; // 是否正在编译(防止多次编译)
const watcher = ["addon.js", "style.scss", "config.js"]
const cache = {};
const pwd = execSync("pwd", { encoding: "utf-8" }).trim()
function cacheFiles(dir) {
readdirSync(dir, { withFileTypes: true }).forEach((file) => {
if (file.isDirectory()) {
cacheFiles(`${dir}/${file.name}`)
} else {
// consola.info(`${chalk.cyan("[Cache]")} Caching ${chalk.green(file.name)}...`)
cache[`${dir}/${file.name}`] = readFileSync(`${dir}/${file.name}`, { encoding: "utf-8" })
}
})
}
cacheFiles(path.resolve(pwd, "./src"))
watcher.forEach((file) => {
// consola.info(`${chalk.cyan("[Cache]")} Caching ${chalk.green(file)}...`)
cache[`${path.resolve(pwd)}/${file}`] = readFileSync(`${file}`, { encoding: "utf-8" })
})
consola.info(`${chalk.cyan("[Cache]")} Caching complete\n`);
watch("./", { recursive: true }, (eventType, filename) => {
if (watcher.includes(filename) || filename.includes("src")) {
// 比对文件内容是否发生变化
if (cache[`${path.resolve(pwd)}/${filename}`] === readFileSync(`${path.resolve(pwd)}/${filename}`, { encoding: "utf-8" })) {
return
}
// 更新缓存
cache[filename] = readFileSync(filename);
consola.info(`${chalk.cyan("[Cache]")} ${chalk.green(filename)} updated`)
// consola.info(`${filename} changed, recompiling...`)
if (isCompiling) {
consola.info(`${chalk.bold(chalk.blue("[Dev]"))} Recompilation in progress, refusing to recompile`)
return;
}
consola.info(`${chalk.bold(chalk.blue("[Dev]"))} Recompiling...`)
isCompiling = true
execSync("sh replace.sh", { stdio: "ignore" });
isCompiling = false
// consola.info("Recompilation complete")
}
})
consola.info(`${chalk.bold(chalk.blue("[Dev]"))} Watching for file changes...`)
consola.info(`${chalk.bold(chalk.blue("[Dev]"))} Press ${chalk.green("Ctrl + C")} to exit`)