feat: support build and runtime ENV configuration
This commit is contained in:
7 files changed
+186
-13
No files matched your search
@@ -1,21 +1,38 @@
|
||||
import { access, writeFile } from 'node:fs/promises'
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { pickPublicEnv } from '../src/site-config.js'
|
||||
import { escapeHtml, pickPublicEnv, resolveSiteConfig } from '../src/site-config.js'
|
||||
|
||||
const outputDirectory = new URL('../dist/', import.meta.url)
|
||||
|
||||
let html
|
||||
let buildEnv
|
||||
try {
|
||||
await access(new URL('index.html', outputDirectory))
|
||||
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/index.html,请先执行 npm run build。')
|
||||
console.error('未找到完整的 dist 构建产物,请先执行 npm run build。')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// Only explicitly supported display variables are written to the public file.
|
||||
const config = JSON.stringify(pickPublicEnv(process.env), null, 2)
|
||||
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)}`)
|
||||
Reference in new issue
Block a user