39 lines
1.7 KiB
JavaScript
39 lines
1.7 KiB
JavaScript
import { readFile, writeFile } from 'node:fs/promises'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { escapeHtml, pickPublicEnv, resolveSiteConfig } from '../src/site-config.js'
|
|
|
|
const outputDirectory = new URL('../dist/', import.meta.url)
|
|
|
|
let html
|
|
let buildEnv
|
|
try {
|
|
html = await readFile(new URL('index.html', outputDirectory), 'utf8')
|
|
buildEnv = JSON.parse(await readFile(new URL('site-config.build.json', outputDirectory), 'utf8'))
|
|
} catch {
|
|
console.error('未找到完整的 dist 构建产物,请先执行 npm run build。')
|
|
process.exit(1)
|
|
}
|
|
|
|
// Only explicitly supported display variables are written to the public file.
|
|
const runtimeEnv = pickPublicEnv(process.env)
|
|
const config = JSON.stringify(runtimeEnv, null, 2)
|
|
.replace(/</g, '\\u003c')
|
|
.replace(/\u2028/g, '\\u2028')
|
|
.replace(/\u2029/g, '\\u2029')
|
|
const outputFile = new URL('runtime-config.js', outputDirectory)
|
|
await writeFile(outputFile, `window.__SITE_CONFIG__ = ${config};\n`, 'utf8')
|
|
|
|
// Keep the HTML metadata consistent for crawlers that do not execute JavaScript.
|
|
const site = resolveSiteConfig(buildEnv, runtimeEnv)
|
|
html = html.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${escapeHtml(site.title)}</title>`)
|
|
for (const [attribute, key, value] of [
|
|
['name', 'description', site.metaDescription],
|
|
['property', 'og:title', site.title],
|
|
['property', 'og:description', site.metaDescription],
|
|
]) {
|
|
const tag = new RegExp(`<meta ${attribute}="${key}" content="[^"]*"\\s*\\/?>`)
|
|
html = html.replace(tag, () => `<meta ${attribute}="${key}" content="${escapeHtml(value)}" />`)
|
|
}
|
|
await writeFile(new URL('index.html', outputDirectory), html, 'utf8')
|
|
console.log(`运行时展示配置已写入 ${fileURLToPath(outputFile)}`)
|