feat(tools): 新增 dev 命令,一键启动前后端开发环境
- npm run dev 同时启动 egg-bin dev(6090) 与 vite(5173),日志按 [backend] / [frontend] 前缀分区 - Ctrl+C / SIGTERM 时结束整棵进程树(Windows 用 taskkill /T /F) - --backend / --frontend 可只启动一端,--no-color 关闭彩色前缀 - 任一端退出时保留另一端继续运行,全部退出后以首个非零退出码返回 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
4b5c228f46
commit
e2d7f04999
@ -33,6 +33,9 @@ npm run init # 生成 config/deploy.config.local.cjs,然后填写 SSH
|
||||
|
||||
| 命令 | 说明 |
|
||||
| --- | --- |
|
||||
| `npm run dev` | **本地开发**:同时启动后端(6090,egg-bin dev)与前端(5173,vite),日志按 `[backend]` / `[frontend]` 分区,Ctrl+C 一并停止 |
|
||||
| `npm run dev:backend` | 只启动后端开发环境 |
|
||||
| `npm run dev:frontend` | 只启动前端开发环境(`/api` 代理到 6090,需后端已启动) |
|
||||
| `npm run deploy` | **前后端同时发布**:构建前端 → 打包前后端 → 上传 → 一次 SSH 完成切换 |
|
||||
| `npm run deploy -- --skip-build` | 复用已有 `frontend/dist`,不重新构建 |
|
||||
| `npm run deploy -- --dry-run` | 只做本地构建与打包,打印远端脚本,不连服务器(同样受 git 约束,可加 `--allow-dirty`) |
|
||||
|
||||
@ -9,6 +9,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"cli": "tsx src/cli.ts",
|
||||
"dev": "tsx src/cli.ts dev",
|
||||
"dev:backend": "tsx src/cli.ts dev:backend",
|
||||
"dev:frontend": "tsx src/cli.ts dev:frontend",
|
||||
"init": "tsx src/cli.ts init",
|
||||
"deploy": "tsx src/cli.ts deploy",
|
||||
"deploy:backend": "tsx src/cli.ts deploy:backend",
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
import 'dotenv/config';
|
||||
import { runDeploy } from './commands/deploy';
|
||||
import { runDev } from './commands/dev';
|
||||
import { runRollback } from './commands/rollback';
|
||||
import { initDeployConfig } from './lib/config';
|
||||
|
||||
@ -10,6 +11,18 @@ interface Command {
|
||||
}
|
||||
|
||||
const COMMANDS: Record<string, Command> = {
|
||||
dev: {
|
||||
summary: '同时启动前后端开发环境 npm run dev [-- --backend|--frontend|--no-color]',
|
||||
run: args => runDev(args, { backend: true, frontend: true }),
|
||||
},
|
||||
'dev:backend': {
|
||||
summary: '只启动后端开发环境 npm run dev:backend',
|
||||
run: args => runDev(args, { backend: true, frontend: false }),
|
||||
},
|
||||
'dev:frontend': {
|
||||
summary: '只启动前端开发环境 npm run dev:frontend',
|
||||
run: args => runDev(args, { backend: false, frontend: true }),
|
||||
},
|
||||
deploy: {
|
||||
summary: '前后端同时发布 npm run deploy [-- --skip-build|--dry-run|--allow-dirty]',
|
||||
run: args => runDeploy(args, { backend: true, frontend: true }),
|
||||
|
||||
145
tools/src/commands/dev.ts
Normal file
145
tools/src/commands/dev.ts
Normal file
@ -0,0 +1,145 @@
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import type { ChildProcess } from 'node:child_process';
|
||||
import { parseArgs } from '../lib/args';
|
||||
import { BACKEND_ROOT, FRONTEND_ROOT } from '../lib/paths';
|
||||
|
||||
export interface DevTargets {
|
||||
backend: boolean;
|
||||
frontend: boolean;
|
||||
}
|
||||
|
||||
interface DevProcess {
|
||||
name: string;
|
||||
child: ChildProcess;
|
||||
}
|
||||
|
||||
const ANSI_RESET = '\u001b[0m';
|
||||
|
||||
/**
|
||||
* 在指定目录启动 npm 脚本(常驻进程)。
|
||||
* Windows 下 npm.cmd 不能直接被 spawn 执行,优先用当前 node 跑 npm-cli.js。
|
||||
*/
|
||||
function spawnNpm(args: string[], cwd: string, detached: boolean): ChildProcess {
|
||||
const npmCli = process.env.npm_execpath;
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
if (npmCli && /npm-cli\.js$/i.test(npmCli)) {
|
||||
return spawn(process.execPath, [ npmCli, ...args ], { cwd, stdio: [ 'ignore', 'pipe', 'pipe' ], detached });
|
||||
}
|
||||
return spawn('npm.cmd', args, { cwd, stdio: [ 'ignore', 'pipe', 'pipe' ], detached, shell: true });
|
||||
}
|
||||
|
||||
return spawn('npm', args, { cwd, stdio: [ 'ignore', 'pipe', 'pipe' ], detached });
|
||||
}
|
||||
|
||||
/** 结束整个进程树(npm → node → egg worker / vite) */
|
||||
function killTree(child: ChildProcess): void {
|
||||
if (!child.pid) return;
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
spawnSync('taskkill', [ '/pid', String(child.pid), '/t', '/f' ], { stdio: 'ignore' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// detached 启动后子进程是独立进程组,负数 pid 可整组结束
|
||||
process.kill(-child.pid, 'SIGTERM');
|
||||
} catch {
|
||||
try {
|
||||
child.kill('SIGTERM');
|
||||
} catch {
|
||||
/* 进程已退出 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 按行加前缀输出 */
|
||||
function pipeWithPrefix(stream: NodeJS.ReadableStream, prefix: string): void {
|
||||
let buffer = '';
|
||||
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk: string) => {
|
||||
buffer += chunk;
|
||||
const lines = buffer.split(/\r?\n/);
|
||||
buffer = lines.pop() ?? '';
|
||||
for (const line of lines) console.log(`${prefix} ${line}`);
|
||||
});
|
||||
stream.on('end', () => {
|
||||
if (buffer) console.log(`${prefix} ${buffer}`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地开发:同时启动后端与前端(也可只启动其中一端)。
|
||||
*
|
||||
* npm run dev # 后端 6090 + 前端 5173
|
||||
* npm run dev:backend
|
||||
* npm run dev:frontend
|
||||
*
|
||||
* 日志按 [backend] / [frontend] 前缀输出,Ctrl+C 一次停止全部。
|
||||
*/
|
||||
export function runDev(args: string[], targets: DevTargets): void {
|
||||
const parsed = parseArgs(args);
|
||||
const color = !parsed.flags.has('no-color');
|
||||
const prefixOf = (name: string, code: string): string => (color ? `${code}[${name}]${ANSI_RESET}` : `[${name}]`);
|
||||
|
||||
// 显式 --backend / --frontend 可缩小范围(默认按命令本身的目标启动)
|
||||
const explicitBackend = parsed.flags.has('backend');
|
||||
const explicitFrontend = parsed.flags.has('frontend');
|
||||
const useBackend = targets.backend && (explicitBackend || !explicitFrontend);
|
||||
const useFrontend = targets.frontend && (explicitFrontend || !explicitBackend);
|
||||
|
||||
const labels: string[] = [];
|
||||
if (useBackend) labels.push('后端 http://localhost:6090');
|
||||
if (useFrontend) labels.push('前端 http://localhost:5173(/api 代理到 6090)');
|
||||
console.log(`[dev] 启动开发环境: ${labels.join(' + ')}`);
|
||||
console.log('[dev] Ctrl+C 同时停止所有开发进程');
|
||||
|
||||
const processes: DevProcess[] = [];
|
||||
|
||||
if (useBackend) {
|
||||
const child = spawnNpm([ 'run', 'dev' ], BACKEND_ROOT, process.platform !== 'win32');
|
||||
processes.push({ name: 'backend', child });
|
||||
pipeWithPrefix(child.stdout!, prefixOf('backend', '\u001b[36m'));
|
||||
pipeWithPrefix(child.stderr!, prefixOf('backend', '\u001b[36m'));
|
||||
}
|
||||
|
||||
if (useFrontend) {
|
||||
const child = spawnNpm([ 'run', 'dev' ], FRONTEND_ROOT, process.platform !== 'win32');
|
||||
processes.push({ name: 'frontend', child });
|
||||
pipeWithPrefix(child.stdout!, prefixOf('frontend', '\u001b[35m'));
|
||||
pipeWithPrefix(child.stderr!, prefixOf('frontend', '\u001b[35m'));
|
||||
}
|
||||
|
||||
let shuttingDown = false;
|
||||
let remaining = processes.length;
|
||||
let exitCode = 0;
|
||||
|
||||
const shutdown = (code: number): void => {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
console.log('\n[dev] 正在停止开发进程…');
|
||||
for (const item of processes) killTree(item.child);
|
||||
process.exitCode = code;
|
||||
// 留一点时间把子进程最后的输出刷出来
|
||||
setTimeout(() => process.exit(code), 500).unref();
|
||||
};
|
||||
|
||||
for (const item of processes) {
|
||||
item.child.on('error', err => {
|
||||
console.error(`${prefixOf(item.name, '')} 无法启动: ${err.message}`);
|
||||
exitCode = exitCode || 1;
|
||||
if (--remaining === 0) shutdown(exitCode);
|
||||
});
|
||||
|
||||
item.child.on('exit', (code, signal) => {
|
||||
if (shuttingDown) return;
|
||||
console.log(`${prefixOf(item.name, '')} 已退出(${code === null ? signal : `code ${code}`})`);
|
||||
if (code !== 0 && code !== null) exitCode = exitCode || code;
|
||||
if (--remaining === 0) shutdown(exitCode);
|
||||
});
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => shutdown(0));
|
||||
process.on('SIGTERM', () => shutdown(0));
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user