为 Halo 主题开发适配本地开发模式
背景
在开发 Halo 主题过程中,新增功能后需要手动打包并上传到 Halo 控制台才能查看效果,流程繁琐、效率低。本文记录为该主题适配本地开发模式的过程,目标是:保存代码即生效,无需打包上传。
方案设计
核心思路是让构建产物直接进入 Halo 的主题目录,配合 Halo Console API 刷新缓存。整体分为三步:
把主题根文件(
theme.yaml、settings.yaml、annotation-setting.yaml、i18n/)同步到HALO_THEMES_DIR/<主题名>/。构建产物
templates/整体复制到HALO_THEMES_DIR/<主题名>/templates/。调用 Halo Console API 重载主题设置与清理模板缓存。
配置集中在项目根目录的 .env.local:
# 开发模式配置:复制为 .env.local 后按需修改(.env.local 不会被提交)
# Halo 的 themes 目录(宿主机路径)。配置后 `pnpm dev` 会把构建产物同步到
# <HALO_THEMES_DIR>/<theme.yaml 中的 metadata.name>/templates,无需打包上传。
# 例如 Docker 挂载:-v D:/halo/themes:/root/.halo2/themes
HALO_THEMES_DIR=D:/halo/themes
# 可选:构建后自动刷新 Halo 主题设置与模板缓存。
# 令牌在 Halo Console「个人中心 → 个人令牌」创建。
HALO_URL=http://localhost:8090
HALO_TOKEN=
其中 HALO_URL 与 HALO_TOKEN 为可选,用于构建后的自动刷新。
核心实现
1. 开发脚本 theme-dev.mjs
脚本负责同步元数据、执行构建、复制产物并刷新 Halo。关键逻辑:
解析
theme.yaml中的metadata.name作为主题目录名。用文件内容比较判断主题根文件是否变化,只有变化时才触发
reload。未配置
HALO_THEMES_DIR时回退为原流程,仅构建到仓库templates/,不影响其他使用者。
脚本由 AI 根据思路进行编写,请仔细阅读后在做参考。
#!/usr/bin/env node
/**
* Halo 主题开发模式:
* 1. 将主题根文件(theme.yaml / settings.yaml / annotation-setting.yaml / i18n)同步到 Halo 的主题目录;
* 2. 直接以 Halo 主题目录下的 templates/ 作为 Astro 构建产物目录(无需复制、无需打包上传);
* 3. 构建成功后按需调用 Halo Console API 重载主题设置与清理模板缓存。
*
* 环境变量见仓库根目录 .env.example。
*/
import { spawnSync } from 'node:child_process';
import { cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
const root = process.cwd();
const themeFiles = ['theme.yaml', 'settings.yaml', 'annotation-setting.yaml'];
const themeDirs = ['i18n'];
// [!code fold:start]
const log = (message) => console.log(`[theme-dev] ${message}`);
function parseThemeName(themeYaml) {
const lines = themeYaml.split(/\r?\n/);
let inMetadata = false;
let metadataIndent = 0;
for (const line of lines) {
if (!line.trim() || line.trimStart().startsWith('#')) {
continue;
}
const metadataMatch = line.match(/^(\s*)metadata:\s*$/);
if (metadataMatch) {
inMetadata = true;
metadataIndent = metadataMatch[1].length;
continue;
}
if (!inMetadata) {
continue;
}
const indent = line.match(/^\s*/)[0].length;
if (indent <= metadataIndent) {
inMetadata = false;
continue;
}
const nameMatch = line.match(/^\s*name:\s*['"]?([^'"\s#]+)['"]?/);
if (nameMatch) {
return nameMatch[1];
}
}
return null;
}
async function copyFileIfChanged(source, target) {
const content = await readFile(source);
let current = null;
try {
current = await readFile(target);
} catch {
// 目标文件不存在时直接写入
}
if (current && current.equals(content)) {
return false;
}
await mkdir(path.dirname(target), { recursive: true });
await writeFile(target, content);
return true;
}
/**
* 同步主题元数据与语言包。返回 theme.yaml / settings.yaml / i18n 是否发生变化,
* 供上层决定是否需要调用 Halo 的 reload 接口。
*/
async function syncThemeFiles(themeDir) {
let metaChanged = false;
for (const file of themeFiles) {
const changed = await copyFileIfChanged(path.join(root, file), path.join(themeDir, file));
if (changed && (file === 'theme.yaml' || file === 'settings.yaml')) {
metaChanged = true;
}
}
for (const dir of themeDirs) {
const changed = await syncDir(path.join(root, dir), path.join(themeDir, dir));
metaChanged = metaChanged || changed;
}
return metaChanged;
}
async function listFiles(dir, baseDir = dir) {
const entries = await readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await listFiles(fullPath, baseDir)));
} else {
files.push(path.relative(baseDir, fullPath));
}
}
return files;
}
async function syncDir(sourceDir, targetDir) {
let changed = false;
for (const relativePath of await listFiles(sourceDir)) {
const fileChanged = await copyFileIfChanged(
path.join(sourceDir, relativePath),
path.join(targetDir, relativePath),
);
changed = changed || fileChanged;
}
return changed;
}
function runAstroBuild() {
const result = spawnSync('pnpm exec astro build', {
cwd: root,
shell: true,
stdio: 'inherit',
env: process.env,
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}
async function callThemeApi(themeName, action, retries = 0) {
const baseUrl = process.env.HALO_URL?.replace(/\/+$/, '');
const token = process.env.HALO_TOKEN;
if (!baseUrl || !token) {
return null;
}
for (let attempt = 0; ; attempt++) {
const response = await fetch(
`${baseUrl}/apis/api.console.halo.run/v1alpha1/themes/${encodeURIComponent(themeName)}/${action}`,
{
method: 'PUT',
headers: { Authorization: `Bearer ${token}` },
},
);
if (response.ok) {
return action;
}
const body = await response.text();
if (attempt >= retries) {
throw new Error(`${action} 失败:${response.status} ${body}`);
}
// Halo 2.27 的 reload 依赖 Setting 资源异步 GC,重试间隔需覆盖 GC 延迟
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
async function refreshTheme(themeName, metaChanged) {
if (!process.env.HALO_URL || !process.env.HALO_TOKEN) {
log('未配置 HALO_URL / HALO_TOKEN,跳过缓存刷新(可手动刷新浏览器,或关闭 Thymeleaf 缓存)');
return;
}
if (metaChanged) {
try {
await callThemeApi(themeName, 'reload', 2);
log('已重新加载主题设置');
} catch (error) {
// 设置重载失败不应阻塞模板刷新
console.warn(`[theme-dev] 重新加载主题设置失败:${error.message}`);
}
}
try {
await callThemeApi(themeName, 'invalidate-cache');
log('已清理主题模板缓存');
} catch (error) {
console.warn(`[theme-dev] 清理模板缓存失败:${error.message}`);
}
}
async function main() {
const themeYaml = await readFile(path.join(root, 'theme.yaml'), 'utf8');
const themeName = parseThemeName(themeYaml);
if (!themeName) {
console.error('[theme-dev] 无法从 theme.yaml 中解析 metadata.name');
process.exit(1);
}
const themesDir = process.env.HALO_THEMES_DIR;
if (!themesDir) {
log('未配置 HALO_THEMES_DIR,按原流程构建到 templates/(不写入 Halo 主题目录)');
runAstroBuild();
await refreshTheme(themeName, false);
return;
}
const themeDir = path.resolve(themesDir, themeName);
const templatesDir = path.join(themeDir, 'templates');
await mkdir(themeDir, { recursive: true });
const metaChanged = await syncThemeFiles(themeDir);
runAstroBuild();
// 先构建到仓库 templates/ 再复制:Astro 的产物整理依赖 rename,跨盘符直接输出会失败。
// 复制前清空目标目录,避免 Halo 主题目录残留已删除页面的旧模板与旧 hash 资源。
await rm(templatesDir, { recursive: true, force: true });
await cp(path.join(root, 'templates'), templatesDir, { recursive: true });
log(`已同步构建产物 → ${templatesDir}`);
await refreshTheme(themeName, metaChanged);
}
main().catch((error) => {
console.error(`[theme-dev] ${error.stack ?? error.message}`);
process.exit(1);
});
2. 跨盘符构建失败
最初尝试让 Astro 直接输出到 Halo 主题目录,结果报错:
EXDEV: cross-device link not permitted, rename 'D:\...\.astro\.prerender\assets\...' -> 'C:\...\templates\assets\...'Astro 整理产物时用 fs.rename 跨盘符移动文件,D 盘到 C 盘必然失败。最终改为:Astro 仍构建到本地 templates/,成功后整体复制到目标目录(复制不受跨盘限制)。
3. Halo API 刷新
Halo 提供了两个关键接口:
PUT /apis/api.console.halo.run/v1alpha1/themes/{name}/reload:重新加载主题设置。PUT /apis/api.console.halo.run/v1alpha1/themes/{name}/invalidate-cache:清理模板缓存。
使用方式
cp .env.example .env.local
pnpm dev
修改 src/、i18n/ 或根目录 yaml 后会自动重建并同步,刷新浏览器即可看到效果。首次使用仍需在 Halo Console 安装并启用该主题;Docker 部署建议同时设置 SPRING_THYMELEAF_CACHE=false。
- 作者: 薛柔零
- 链接: https://blog.xuezero.com/archives/wz3hMNo5
- 版权: 除特别声明外,本文采用 CC BY-NC-SA 4.0 许可协议进行许可,转载请注明出处。