From 7de5280824f99392fa9c8625e13c9ee80b81dc2d Mon Sep 17 00:00:00 2001
From: hkfires <10558748+hkfires@users.noreply.github.com>
Date: Wed, 15 Oct 2025 16:49:53 +0800
Subject: [PATCH] feat(build): auto-inject release version into HTML output
---
.github/workflows/release.yml | 2 ++
build.js | 34 ++++++++++++++++++++++++++++++++++
index.html | 2 +-
3 files changed, 37 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ebbf7a9..7579e8b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -27,6 +27,8 @@ jobs:
- name: Build all-in-one HTML
run: npm run build
+ env:
+ VERSION: ${{ github.ref_name }}
- name: Prepare release assets
run: |
diff --git a/build.js b/build.js
index 283a064..8453a65 100644
--- a/build.js
+++ b/build.js
@@ -49,6 +49,35 @@ function escapeForStyle(content) {
return content.replace(/<\/(style)/gi, '<\\/$1');
}
+function getVersion() {
+ // 1. 优先从环境变量获取(GitHub Actions 会设置)
+ if (process.env.VERSION) {
+ return process.env.VERSION;
+ }
+
+ // 2. 尝试从 git tag 获取
+ try {
+ const { execSync } = require('child_process');
+ const gitTag = execSync('git describe --tags --exact-match 2>/dev/null || git describe --tags 2>/dev/null || echo ""', { encoding: 'utf8' }).trim();
+ if (gitTag) {
+ return gitTag;
+ }
+ } catch (err) {
+ console.warn('无法从 git 获取版本号');
+ }
+
+ // 3. 回退到 package.json
+ try {
+ const packageJson = JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'));
+ return 'v' + packageJson.version;
+ } catch (err) {
+ console.warn('无法从 package.json 读取版本号');
+ }
+
+ // 4. 最后使用默认值
+ return 'v0.0.0-dev';
+}
+
function ensureDistDir() {
if (fs.existsSync(distDir)) {
fs.rmSync(distDir, { recursive: true, force: true });
@@ -82,6 +111,11 @@ function build() {
const css = escapeForStyle(readFile(sourceFiles.css));
const i18n = escapeForScript(readFile(sourceFiles.i18n));
const app = escapeForScript(readFile(sourceFiles.app));
+
+ // 获取版本号并替换
+ const version = getVersion();
+ console.log(`使用版本号: ${version}`);
+ html = html.replace(/__VERSION__/g, version);
html = html.replace(
'',
diff --git a/index.html b/index.html
index ae644c1..4704f5b 100644
--- a/index.html
+++ b/index.html
@@ -785,7 +785,7 @@