oms/frontend/scripts/deploy.mjs
liufumingren 441659d303 feat(frontend): 新增蓝绿发布脚本与生产 API 地址
发布:
- 新增 scripts/deploy.mjs、rollback.mjs、init-config.mjs 与 scripts/remote/{deploy,rollback}.sh
  · 服务器上按 releases/<版本号> 存放,current 软链原子切换,发布/回滚都不中断服务
  · 切换前校验 index.html 与引用的 /assets 资源完整,并补齐历史版本静态资源(旧 chunk 不 404)
  · 真实配置 scripts/deploy.config.json 已加入忽略清单,模板 deploy.config.example.json 入库
- package.json 增加 deploy / rollback / deploy:init

接口地址:
- 新增 .env.production(VITE_API_BASE_URL=https://api.oms.gztbyc.com/api)与 .env.development
  (/api,继续走 vite 代理到本地 6090)
- request.ts 的 baseURL 改为读 VITE_API_BASE_URL;env.d.ts 声明 ImportMetaEnv
- 新增 utils/media.ts#mediaUrl:跨域部署时把后端返回的相对地址(/api/files/raw/…)
  补全为 API 站点绝对地址,用于 ImageUploader、商品列表图片、主体账号头像渲染

工程:
- tsconfig 去掉已弃用的 baseUrl(TS 7 将移除;paths 自 TS 4.1 起不再依赖它)
- .gitignore 增加 dist.tar.gz 与真实部署配置
2026-09-14 22:14:27 +08:00

137 lines
6.1 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
/**
* OMS 前端蓝绿发布脚本(Windows / macOS / Linux 通用)
*
* 发布原理:
* 1. 本地构建 dist,压缩后上传到服务器 `${basePath}/releases/<版本号>/`(全新目录,不触碰线上目录)
* 2. 服务器上解压并做完整性校验,再把历史版本的静态资源补齐(旧 chunk 不 404)
* 3. 通过 `current` 软链接「先建临时链接再 mv 改名」原子切换,切换瞬间服务不中断
* 4. 健康检查(仅提示)并清理超出保留数量的旧版本
*
* 依赖本机已安装:ssh、scp、tar(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
*
* 用法:
* npm run deploy 构建 + 发布
* npm run deploy -- --skip-build 跳过本地构建,直接发布现有 dist(调试用)
*/
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 PROJECT_ROOT = path.resolve(__dirname, '..');
// --- 配置(读取独立配置文件,该文件不纳入版本控制) ---
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
const EXAMPLE_PATH = path.join(__dirname, 'deploy.config.example.json');
if (!existsSync(CONFIG_PATH)) {
console.error('❌ 缺少配置文件 scripts/deploy.config.json');
console.error(` 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。`);
console.error(` 模板路径:${EXAMPLE_PATH}`);
process.exit(1);
}
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
// --- 配置校验 ---
const REQUIRED_KEYS = ['user', 'ip', 'basePath', 'siteHost'];
const missingKeys = REQUIRED_KEYS.filter((k) => !config[k]);
if (missingKeys.length) {
console.error(`❌ scripts/deploy.config.json 缺少必填项:${missingKeys.join(', ')}`);
console.error(' 参考 scripts/deploy.config.example.json 补齐。');
process.exit(1);
}
const SKIP_BUILD = process.argv.includes('--skip-build');
const USER = config.user;
const IP = config.ip; // 服务器 IP
const BASE_PATH = config.basePath; // 站点在服务器上的存放路径(releases/current 都在其下)
const KEEP_RELEASES = Number(config.keepReleases) > 0 ? Number(config.keepReleases) : 5; // 服务器保留的最近版本数
const SITE_HOST = config.siteHost; // 发版后健康检查域名
const LOCAL_DIST = path.join(PROJECT_ROOT, 'dist');
const SSH_KEY = resolveSshKey(config.sshKey);
const SSH_OPTS = ['-o', 'StrictHostKeyChecking=no', ...(SSH_KEY ? ['-i', SSH_KEY] : [])];
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())}`;
}
/** sshKey 支持「绝对路径」与「~/.ssh 下的文件名」;留空则用 ssh 默认密钥/agent */
function resolveSshKey(value) {
if (!value) return '';
if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1));
return path.isAbsolute(value) ? value : path.join(os.homedir(), '.ssh', value);
}
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(`🚀 开始发布 OMS 前端,版本: ${RELEASE_NAME}`);
console.log(` 目标:${HOST}:${REMOTE_RELEASE}`);
try {
// 1. 本地打包(失败立即中止,防止把坏产物发到线上)
if (SKIP_BUILD) {
console.log('⏭️ 已跳过本地构建(--skip-build)');
} else {
run(NPM, ['run', 'build'], { cwd: PROJECT_ROOT });
}
// 2. 校验本地产物完整性
if (!existsSync(path.join(LOCAL_DIST, 'index.html')) || !existsSync(path.join(LOCAL_DIST, 'assets'))) {
console.error('❌ 本地构建产物不完整(缺少 index.html 或 assets),中止发布');
process.exit(1);
}
// 3. 压缩并上传到服务器上的新版本目录(全程不触碰 current 指向的线上目录)
run('tar', ['-czf', TARBALL, '-C', LOCAL_DIST, '.'], { cwd: PROJECT_ROOT });
run('ssh', [...SSH_OPTS, HOST, `mkdir -p '${REMOTE_RELEASE}'`]);
run('scp', [...SSH_OPTS, path.join(PROJECT_ROOT, 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(path.join(PROJECT_ROOT, TARBALL), { force: true });
}