外观
开发
本地开发时执行下列命令即可。
全量开发(不含 SSG 着陆页/文档站开发):
bash
npm run dev1
SSG 着陆页/文档站开发:
bash
# 将 `blog` 换成实际的目录名
cross-env TASKS=ssg:blog node --run dev1
2
2
Nuxt SSR 独立站开发:
bash
npm run dev:ssr1
导航站开发服务绑定开发环境自动解析的 SERVER_HOST,可通过 http://{SERVER_HOST}:9890 从本机或同一局域网访问。
支持 TASKS 参数
该命令支持通过 TASKS 来指定具体执行哪些任务(不传的话默认执行全部任务)。
该参数支持白名单和黑名单模式,并且支持 * 通配符。注意,白名单和黑名单模式不可混用,以避免歧义。
bash
# 白名单:执行所有 spa: 开头的任务
cross-env TASKS=spa:* npm run <example-command>
# 白名单:混合精确匹配和通配符
cross-env TASKS=clean,ssg:* npm run <example-command>
# 黑名单:排除所有 spa: 开头的任务
cross-env TASKS=-spa:* npm run <example-command>1
2
3
4
5
6
2
3
4
5
6
发布正式环境应尽量使用内网地址
在正式环境,能通过内网连接的服务(比如数据库),应尽可能都使用内网地址来访问。
scripts/dev.mts 源码
typescript
import { logInfo, logWarn, joinPath, isPathExists } from "nsuite";
import { writeSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import open from "open";
import {
APP_FRONT_PORT,
HEALTH_CHECK_PATH,
OPEN_PATH_IN_DEV,
PATH_APPS_HOME,
PATH_PUBLIC,
PATH_ROOT,
REDIS_HOST,
REDIS_PORT,
POSTGRES_PORT,
SERVER_HOST,
SERVER_PORT,
SSH_HOST,
SSH_PORT,
SSH_USERNAME,
SSH_PASSWORD,
STANDALONE_APPS_PORT,
STANDALONE_SSG_APPS_NAMES,
STANDALONE_SSR_APPS,
SUB_APPS,
} from "#utils/ConstantUtils";
import { cleanAllBuildFiles } from "#scripts/utils/clean-files";
import { runCommandInChildProcess, killAllChildProcessList } from "#scripts/utils/child-process";
import { buildPublic, checkServerHealth, reloadOnFilesChange } from "#scripts/utils/public-builder";
import { useTask } from "#scripts/utils/use-task";
import { waitForPort } from "#scripts/utils/use-dev";
const allowTasks = process.env.TASKS || "";
const isGitBash = Boolean(process.env.MSYSTEM);
const sshAskpassPath = joinPath(
PATH_ROOT,
`scripts/utils/ssh-askpass.${isGitBash ? "sh" : "cmd"}`,
);
const { killAllChildProcessWhenSuitable, addTask, runTasksSequentially, printTaskStatisticsInfo } =
useTask({ allowTasks });
/**
* 异常时关闭所有子进程
*/
killAllChildProcessWhenSuitable();
/**
* 停机标志:SIGINT/SIGTERM 或异常退出时置位,
* 避免清理阶段杀掉 ssh 被误判为隧道意外断开而触发重连
*/
let isShuttingDown = false;
process.on("SIGINT", () => {
isShuttingDown = true;
});
process.on("SIGTERM", () => {
isShuttingDown = true;
});
/**
* 兜底处理未捕获异常:同步打印错误并清理子进程后退出,
* 避免主进程静默死亡留下孤儿进程(vite、ssh 隧道等)
*/
const writeErrorAndExit = (message: string) => {
isShuttingDown = true;
// 使用 writeSync 同步写入,避免 process.exit 丢失缓冲区中的输出
writeSync(2, `${message}\n`);
void killAllChildProcessList().finally(() => process.exit(1));
};
process.on("uncaughtException", (error) => {
writeErrorAndExit(`[dev] 未捕获异常,进程即将退出: ${error.stack || error.message}`);
});
process.on("unhandledRejection", (reason) => {
const message = reason instanceof Error ? (reason.stack || reason.message) : String(reason);
writeErrorAndExit(`[dev] 未处理的 Promise rejection,进程即将退出: ${message}`);
});
/**
* 编译开始前先清空所有可能遗留的编译产物
*/
addTask("cleanAllBuildFiles", async () => {
await cleanAllBuildFiles();
});
/**
* 重连等待时间(毫秒)
*/
const SSH_RECONNECT_DELAY_MS = 2000;
/**
* 启动 SSH 隧道子进程
*/
const spawnSshTunnel = (): { promise: Promise<number | null> } => {
const { promise } = runCommandInChildProcess({
appName: "sshTunnel",
command: "ssh",
args: [
"-o StrictHostKeyChecking=accept-new",
"-o ExitOnForwardFailure=yes",
// 心跳保活:死连接约 1 分钟内暴露,避免 NAT/网络切换后隧道半开悬挂
"-o ServerAliveInterval=15",
"-o ServerAliveCountMax=4",
// Redis 端口转发
`-L ${REDIS_PORT}:localhost:6379`,
// PostgreSQL 端口转发
`-L ${POSTGRES_PORT}:localhost:5432`,
`-p ${SSH_PORT} ${SSH_USERNAME}@${SSH_HOST} -N`,
].join(" "),
env: {
...process.env,
DISPLAY: "localhost:0",
SSH_ASKPASS: sshAskpassPath,
SSH_ASKPASS_REQUIRE: SSH_PASSWORD ? "force" : "never",
},
});
return { promise };
};
/**
* 等待隧道端口就绪,或 SSH 进程异常退出
*/
const waitSshTunnelReady = async (sshExit: Promise<number | null>): Promise<void> => {
await Promise.race([
sshExit.then((code) => {
if (code) {
throw new Error(`SSH 隧道异常退出: code=${code}`);
}
}),
Promise.all([waitForPort(REDIS_PORT), waitForPort(POSTGRES_PORT)]),
]);
};
/**
* 监督 SSH 隧道:意外断开后延迟自动重连,直到进程停机
*/
const superviseSshTunnel = async (firstExit: Promise<number | null>): Promise<void> => {
let sshExit = firstExit;
while (!isShuttingDown) {
const code = await sshExit;
if (isShuttingDown) {
return;
}
logWarn(
`[sshTunnel] SSH 隧道已断开 (code=${code}),${SSH_RECONNECT_DELAY_MS / 1000} 秒后自动重连`,
);
await sleep(SSH_RECONNECT_DELAY_MS);
if (isShuttingDown) {
return;
}
try {
const spawned = spawnSshTunnel();
await waitSshTunnelReady(spawned.promise);
sshExit = spawned.promise;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logWarn(`[sshTunnel] 重连失败: ${message},继续重试`);
await sleep(SSH_RECONNECT_DELAY_MS);
}
}
};
/**
* SSH 端口转发隧道
*/
addTask("sshTunnel", async () => {
const { promise: sshExit } = spawnSshTunnel();
// 启动失败视为致命错误,中断 dev
await waitSshTunnelReady(sshExit);
// 启动成功后监督隧道,意外断开时自动重连,避免 Redis/PostgreSQL 持续连接失败
void superviseSshTunnel(sshExit);
});
/**
* 启动主服务
*/
addTask("server", async (payload) => {
const { progress, taskName } = payload;
const { promise } = runCommandInChildProcess({
appName: `${progress.current}/${progress.total}-${taskName}`,
command: "node",
args: "./scripts/utils/server-watcher.mts",
env: process.env,
onStdout: (data: string, resolve) => {
if (data.includes("Server is running on port")) {
resolve(0);
}
},
});
const exitCode = await promise;
if (exitCode) {
throw new Error(`Task ${taskName} failed: exitCode=${exitCode}`);
}
});
/**
* 启动消费者服务
*/
addTask("consumer-bugs", async (payload) => {
const { taskName, progress } = payload;
const { promise } = runCommandInChildProcess({
appName: `${progress.current}/${progress.total}-${taskName}`,
command: "node",
args: `--watch --watch-preserve-output ./consumers/bugs.mts`,
env: process.env,
onStdout: (data: string, resolve) => {
if (data.includes("成功启动bugs相关队列消费脚本")) {
resolve(0);
}
},
});
const exitCode = await promise;
if (exitCode) {
throw new Error(`Task ${taskName} failed: exitCode=${exitCode}`);
}
});
/**
* 顺序启动 SPA apps
*/
for (const app of SUB_APPS) {
const { appName, appPort } = app;
addTask(appName, async (payload) => {
const { progress, taskName } = payload;
const { promise } = runCommandInChildProcess({
appName: `${progress.current}/${progress.total}-SPA-${appName}`,
command: "cross-env",
args: `APP_NAME=${appName} PORT=${appPort} vite serve ./apps/${appName}`,
env: process.env,
onStdout: (data: string, resolve) => {
// vite ready 输出 "ready in xxx";"to show help" 仅在 TTY 终端打印,非交互环境以此兜底
if (data.includes("to show help") || data.includes("ready in")) {
resolve(0);
}
},
});
const exitCode = await promise;
if (exitCode) {
throw new Error(`Task ${taskName} failed: exitCode=${exitCode}`);
}
});
}
if (allowTasks) {
const allAllowTasks = allowTasks.split(",");
const ssgTask = allAllowTasks.find((taskName) => taskName.startsWith("ssg:"));
if (ssgTask) {
const appName = ssgTask.split(":")[1] || "";
if (STANDALONE_SSG_APPS_NAMES.includes(appName)) {
addTask(ssgTask, async (payload) => {
const { progress, taskName } = payload;
// 区分应用类型:Next.js、Nuxt 4 应用、VitePress 2 应用
const pathApp = joinPath(PATH_APPS_HOME, appName);
const pathNuxtConfig = joinPath(pathApp, "nuxt.config.ts");
const pathNextConfig = joinPath(pathApp, "next.config.ts");
const isNext = await isPathExists(pathNextConfig);
const isNuxt = await isPathExists(pathNuxtConfig);
const args = isNext
? `APP_NAME=${appName} PORT=${STANDALONE_APPS_PORT} SERVER_HOST=${SERVER_HOST} SERVER_PORT=${SERVER_PORT} next dev ./apps-home/${appName}`
: isNuxt
? `APP_NAME=${appName} PORT=${STANDALONE_APPS_PORT} nuxt dev --cwd=./apps-home/${appName}`
: `PORT=${STANDALONE_APPS_PORT} vitepress dev ./apps-home/${appName}/config`;
const { promise } = runCommandInChildProcess({
appName: `${progress.current}/${progress.total}-SSG-${taskName}`,
command: "cross-env",
args,
env: process.env,
});
const exitCode = await promise;
if (exitCode) {
throw new Error(`Task ${taskName} failed: exitCode=${exitCode}`);
}
});
}
}
}
if (allowTasks) {
const allAllowTasks = allowTasks.split(",");
const ssrTask = allAllowTasks.find((taskName) => taskName.startsWith("ssr:"));
if (ssrTask) {
const appName = ssrTask.split(":")[1] || "";
const app = STANDALONE_SSR_APPS.find((item) => item.appName === appName);
if (app) {
addTask(ssrTask, async (payload) => {
const { progress, taskName } = payload;
const args = `APP_NAME=${appName} PORT=${app.appPort} nuxt dev --host ${SERVER_HOST} --cwd=./apps-home/${appName}`;
const { promise } = runCommandInChildProcess({
appName: `${progress.current}/${progress.total}-SSR-${appName}`,
command: "cross-env",
args,
env: process.env,
});
const exitCode = await promise;
if (exitCode) {
throw new Error(`Task ${taskName} failed: exitCode=${exitCode}`);
}
});
}
}
}
/**
* 启动 public 目录下 js/*.mts 和 css/*.scss 文件的实时编译
*/
addTask("browerSync", async () => {
await checkServerHealth({
healthCheckUrl: `http://${SERVER_HOST}:${SERVER_PORT}${HEALTH_CHECK_PATH}`,
conditionCallback: (res) => res.data.code === 200,
interval: 1000,
});
const browserSync = reloadOnFilesChange([
joinPath(PATH_PUBLIC, "js/**/*.min.js"),
joinPath(PATH_PUBLIC, "css/**/*.min.css"),
joinPath(PATH_ROOT, "views/**/*.ejs"),
]);
// 监听 browser-sync 错误事件(如端口被占用),
// 避免无监听器的 error 事件以未捕获异常形式导致主进程静默崩溃
let initReject: ((error: Error) => void) | undefined;
browserSync.emitter.on("error", (error: Error) => {
writeSync(2, `[browerSync] browser-sync 运行错误: ${error.stack || error.message}\n`);
initReject?.(error);
});
await new Promise<void>((resolve, reject) => {
initReject = reject;
browserSync.init(
{
port: APP_FRONT_PORT,
// listen 决定端口探测 host:默认 localhost 会在 Node 22 下因
// 多地址连接失败返回 AggregateError,触发 browser-sync 内部
// process.exit(1) 静默终止 dev 主进程,必须显式指定为 IPv4 地址
listen: SERVER_HOST,
online: true,
open: false,
notify: false,
// @ts-ignore
ws: true,
proxy: `${SERVER_HOST}:${SERVER_PORT}`,
},
(error) => {
if (error) {
reject(error);
return;
}
resolve();
},
);
});
await buildPublic({
enableWatch: true,
});
});
await runTasksSequentially();
printTaskStatisticsInfo();
if (OPEN_PATH_IN_DEV) {
const openUrl = `http://${SERVER_HOST}:${APP_FRONT_PORT}${OPEN_PATH_IN_DEV}`;
const localUrl = `http://localhost:${APP_FRONT_PORT}${OPEN_PATH_IN_DEV}`;
await open(openUrl);
logInfo(`\n🚀 启动成功,请访问: ${openUrl} 或 ${localUrl}`);
}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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366