WEB/scripts/deploy.mjs
liufumingren 81b663de63 fix: 打包报错修复与部署脚本 Windows 跨平台化
- 修复 TS1261 import 大小写(33 处)、TS2561 report_code→report_id、TS2339 类型标注
- deploy/rollback 支持 Windows: npm.cmd EINVAL(改用 node 直跑 npm-cli.js)、sshKey 绝对路径
- map.ts 兼容后端菜单老路径,强制指向 basicManagement newview(含投递计划/报表定义)
- report.deliveryPlan.copy 返回结构对齐后端 created/skipped,修正前端误报复制成功
2026-08-30 09:29:57 +08:00

110 lines
4.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
/**
* 跨平台发布脚本(Windows / macOS / Linux 通用)
*
* 等价于原 deploy.sh,改用 Node.js 实现,使 Windows 开发环境无需安装 sh/bash。
* 依赖本机已安装:ssh、scp、tar(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
*
* 用法:npm run deploy
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// --- 配置(读取独立配置文件,该文件不纳入版本控制) ---
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
if (!existsSync(CONFIG_PATH)) {
console.error('❌ 缺少配置文件 deploy.config.json');
console.error(' 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。');
process.exit(1);
}
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
const USER = config.user;
const IP = config.ip; // 服务器 IP
const BASE_PATH = config.basePath; // 项目在服务器上的存放路径
const KEEP_RELEASES = config.keepReleases; // 服务器上保留的最近版本数
const SITE_HOST = config.siteHost; // 发版后健康检查域名
const LOCAL_DIST = path.resolve('dist');
const SSH_KEY = path.isAbsolute(config.sshKey) ? config.sshKey : path.join(os.homedir(), '.ssh', config.sshKey);
const SSH_OPTS = ['-i', SSH_KEY, '-o', 'StrictHostKeyChecking=no'];
const HOST = `${USER}@${IP}`;
const TARBALL = 'dist.tar.gz';
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const RELEASE_NAME = `v${timestamp()}_${process.pid}`; // 版本号(带 PID,避免并发/重复发布冲突)
const REMOTE_RELEASE = `${BASE_PATH}/releases/${RELEASE_NAME}`;
function timestamp() {
const d = new Date();
const p = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
}
function run(cmd, args, opts = {}) {
// Windows 下 .cmd/.bat(如 npm.cmd)不能直接用 spawnSync 执行(报 EINVAL):
// 优先用 node 直接运行 npm-cli.js(无 shell、无 DEP0190 警告),否则回退到 shell: true
const isWinCmd = process.platform === 'win32' && /\.(cmd|bat)$/i.test(cmd)
let res
if (isWinCmd) {
const npmCli = process.env.npm_execpath
if (npmCli && /npm-cli\.js$/i.test(npmCli)) {
res = spawnSync(process.execPath, [npmCli, ...args], { stdio: 'inherit', ...opts })
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', shell: true, ...opts })
}
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', ...opts })
}
if (res.error) {
console.error(`❌ 无法执行命令 ${cmd}: ${res.error.message}`);
if (res.error.code === 'ENOENT') {
console.error(
' 请确认本机已安装对应命令(ssh/scp/tar)。Windows 10 1803+ 自带 OpenSSH 客户端与 tar。'
);
}
process.exit(1);
}
if (res.status !== 0) process.exit(res.status ?? 1);
}
console.log(`🚀 开始发布版本: ${RELEASE_NAME}`);
try {
// 1. 本地打包(失败立即中止,防止把坏产物发到线上)
run(NPM, ['run', 'build']);
// 2. 校验本地产物完整性
if (!existsSync(path.join(LOCAL_DIST, 'index.html')) || !existsSync(path.join(LOCAL_DIST, 'assets'))) {
console.error('❌ 本地构建产物不完整(缺少 index.html 或 assets),中止发布');
process.exit(1);
}
// 3. 压缩并上传到独立的新版本目录(全程不触碰当前运行目录)
run('tar', ['-czf', TARBALL, '-C', LOCAL_DIST, '.']);
run('ssh', [...SSH_OPTS, HOST, `mkdir -p '${REMOTE_RELEASE}'`]);
run('scp', [...SSH_OPTS, TARBALL, `${HOST}:${REMOTE_RELEASE}/${TARBALL}`]);
// 4. 远程:解压 → 校验 → 补齐旧资源 → 原子切换 → 健康检查 → 清理
const remoteScript = readFileSync(path.join(__dirname, 'remote', 'deploy.sh'), 'utf8');
run(
'ssh',
[
...SSH_OPTS,
HOST,
`RELEASE='${REMOTE_RELEASE}' BASE='${BASE_PATH}' KEEP=${KEEP_RELEASES} HOST='${SITE_HOST}' bash -s`,
],
{ input: remoteScript, stdio: ['pipe', 'inherit', 'inherit'] }
);
console.log(`✨ 发布成功!当前版本: ${RELEASE_NAME}`);
} finally {
// 无论成功失败都清理本地临时压缩包
rmSync(TARBALL, { force: true });
}