feat: support build and runtime ENV configuration
This commit is contained in:
7 files changed
+186
-13
No files matched your search
@@ -7,10 +7,13 @@
|
|||||||
使用 Node.js 20.19+ 或 22.12+:
|
使用 Node.js 20.19+ 或 22.12+:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
cp .env.example .env.local
|
||||||
npm install
|
npm install
|
||||||
npm run dev
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
|
编辑 `.env.local` 后重启开发服务器。
|
||||||
|
|
||||||
项目的 `.npmrc` 启用了 `legacy-peer-deps`,用于绕过 npm 10 在解析 Vite 可选开发工具同伴依赖时触发的 `Cannot read properties of null (reading 'edgesOut')` 错误。直接运行上述安装命令即可。
|
项目的 `.npmrc` 启用了 `legacy-peer-deps`,用于绕过 npm 10 在解析 Vite 可选开发工具同伴依赖时触发的 `Cannot read properties of null (reading 'edgesOut')` 错误。直接运行上述安装命令即可。
|
||||||
|
|
||||||
## 构建与预览
|
## 构建与预览
|
||||||
@@ -22,11 +25,71 @@ npm run preview
|
|||||||
|
|
||||||
部署时发布 `dist` 目录。
|
部署时发布 `dist` 目录。
|
||||||
|
|
||||||
## 调整内容
|
## ENV 展示配置
|
||||||
|
|
||||||
- `src/main.js`:品牌名称、页面文案、准备阶段和分享内容。
|
开发和构建时由 Vite 读取 `.env`、`.env.local` 及对应模式的文件,例如 `.env.production`;进程环境变量优先于文件配置。配置示例见 `.env.example`。
|
||||||
|
|
||||||
|
| 环境变量 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `VITE_PROJECT_NAME` | 中文项目名称,默认“未完待续” |
|
||||||
|
| `VITE_PROJECT_NAME_EN` | 英文名称,留空隐藏 |
|
||||||
|
| `VITE_PROJECT_DESCRIPTION` | 项目介绍,同步用于页面正文、分享文案和描述元信息;支持换行 |
|
||||||
|
| `VITE_PAGE_TITLE` | 浏览器和分享标题,留空时由项目名自动生成 |
|
||||||
|
| `VITE_HEADER_NOTE` | 页眉说明文案,留空隐藏文字 |
|
||||||
|
| `VITE_COPYRIGHT` | 版权声明,支持 `{year}` 和 `{projectName}` 占位符;留空隐藏 |
|
||||||
|
| `VITE_FOOTER_NOTE` | 页脚附加文案,留空隐藏 |
|
||||||
|
| `VITE_ICP_NUMBER` | ICP 备案号,留空不显示 |
|
||||||
|
| `VITE_ICP_URL` | ICP 查询链接,默认为工信部备案网站 |
|
||||||
|
| `VITE_PUBLIC_SECURITY_NUMBER` | 公安备案号,留空不显示 |
|
||||||
|
| `VITE_PUBLIC_SECURITY_URL` | 公安备案查询链接,未填写则仅显示备案号文字 |
|
||||||
|
|
||||||
|
构建时也可以直接传入 ENV:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
VITE_PROJECT_NAME="我的项目" \
|
||||||
|
VITE_COPYRIGHT='© {year} 我的团队 · 保留所有权利' \
|
||||||
|
VITE_ICP_NUMBER="你的实际备案号" \
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
项目名称会同步到页眉、默认版权、浏览器标题及分享内容。备案号为空时不展示对应条目;配置链接时可点击打开查询页面。
|
||||||
|
|
||||||
|
## 运行时注入
|
||||||
|
|
||||||
|
已构建的页面也可以覆盖展示配置,无需重新打包。配置优先级为:**运行时 ENV > 构建时 ENV > 默认内容**。运行时显式传入空字符串,可以清空构建时的可选内容。
|
||||||
|
|
||||||
|
本地验证运行时配置:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run build
|
||||||
|
VITE_PROJECT_NAME="运行时项目" \
|
||||||
|
VITE_COPYRIGHT='© {year} 运行时团队' \
|
||||||
|
VITE_ICP_NUMBER="你的实际备案号" \
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
`npm start` 会先读取当前进程的展示 ENV、写入 `dist/runtime-config.js` 并同步更新 HTML 元信息,再启动 Vite 预览服务器。`npm run preview` 只预览现有构建产物,不重新注入配置。
|
||||||
|
|
||||||
|
使用 Nginx 或其他静态服务器时,在启动静态服务器之前执行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
VITE_PROJECT_NAME="运行时项目" npm run config:runtime
|
||||||
|
```
|
||||||
|
|
||||||
|
注入命令需要 Node.js,且只读取**进程环境变量**;不会重新加载 `.env` 文件。发布完整的 `dist` 目录,并为 `runtime-config.js` 和 `index.html` 设置重新验证缓存的策略。静态页面本身不会直接读取服务器 ENV,部署入口需要先执行注入命令。再次执行注入时,未指定的变量恢复为原来的构建配置。
|
||||||
|
|
||||||
|
上述配置均为浏览器可访问的公开展示信息;注入脚本只导出表格中列出的变量。更改运行时配置后,刷新页面生效。
|
||||||
|
|
||||||
|
## 修改样式与验证
|
||||||
|
|
||||||
|
- `src/site-config.js`:展示配置、默认值和 ENV 优先级。
|
||||||
|
- `src/main.js`:页面结构、准备阶段和分享交互。
|
||||||
- `src/style.css`:颜色变量、星球插画、动效和响应式布局。
|
- `src/style.css`:颜色变量、星球插画、动效和响应式布局。
|
||||||
- `index.html`:浏览器标题、页面描述和社交分享元信息。
|
|
||||||
- `public/favicon.svg`:网站图标。
|
- `public/favicon.svg`:网站图标。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm test
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
分享按钮优先调用浏览器的系统分享;不可用时复制链接。复制权限受限时展示可手动复制的链接。页面使用系统字体与 CSS/SVG 插画,无需外部图片或字体服务。
|
分享按钮优先调用浏览器的系统分享;不可用时复制链接。复制权限受限时展示可手动复制的链接。页面使用系统字体与 CSS/SVG 插画,无需外部图片或字体服务。
|
||||||
+1
-1
@@ -5,6 +5,7 @@
|
|||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="theme-color" content="#f7f7ef" />
|
<meta name="theme-color" content="#f7f7ef" />
|
||||||
|
<script src="%BASE_URL%runtime-config.js"></script>
|
||||||
<meta name="description" content="__SITE_DESCRIPTION__" />
|
<meta name="description" content="__SITE_DESCRIPTION__" />
|
||||||
<meta property="og:type" content="website" />
|
<meta property="og:type" content="website" />
|
||||||
<meta property="og:locale" content="zh_CN" />
|
<meta property="og:locale" content="zh_CN" />
|
||||||
@@ -14,7 +15,6 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
<script src="%BASE_URL%runtime-config.js"></script>
|
|
||||||
<script type="module" src="/src/main.js"></script>
|
<script type="module" src="/src/main.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+2
-1
@@ -8,7 +8,8 @@
|
|||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"config:runtime": "node scripts/write-runtime-config.js",
|
"config:runtime": "node scripts/write-runtime-config.js",
|
||||||
"start": "npm run config:runtime && vite preview --host 0.0.0.0"
|
"start": "npm run config:runtime && vite preview --host 0.0.0.0",
|
||||||
|
"test": "node --test"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"vite": "^8.3.4"
|
"vite": "^8.3.4"
|
||||||
|
|||||||
@@ -1,21 +1,38 @@
|
|||||||
import { access, writeFile } from 'node:fs/promises'
|
import { readFile, writeFile } from 'node:fs/promises'
|
||||||
import { fileURLToPath } from 'node:url'
|
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)
|
const outputDirectory = new URL('../dist/', import.meta.url)
|
||||||
|
|
||||||
|
let html
|
||||||
|
let buildEnv
|
||||||
try {
|
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 {
|
} catch {
|
||||||
console.error('未找到 dist/index.html,请先执行 npm run build。')
|
console.error('未找到完整的 dist 构建产物,请先执行 npm run build。')
|
||||||
process.exit(1)
|
process.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only explicitly supported display variables are written to the public file.
|
// 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(/</g, '\\u003c')
|
||||||
.replace(/\u2028/g, '\\u2028')
|
.replace(/\u2028/g, '\\u2028')
|
||||||
.replace(/\u2029/g, '\\u2029')
|
.replace(/\u2029/g, '\\u2029')
|
||||||
const outputFile = new URL('runtime-config.js', outputDirectory)
|
const outputFile = new URL('runtime-config.js', outputDirectory)
|
||||||
await writeFile(outputFile, `window.__SITE_CONFIG__ = ${config};\n`, 'utf8')
|
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)}`)
|
console.log(`运行时展示配置已写入 ${fileURLToPath(outputFile)}`)
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
import './style.css'
|
import './style.css'
|
||||||
import { escapeHtml, resolveSiteConfig } from './site-config.js'
|
import { escapeHtml, resolveSiteConfig } from './site-config.js'
|
||||||
|
|
||||||
const site = resolveSiteConfig(import.meta.env, window.__SITE_CONFIG__)
|
const site = resolveSiteConfig(__SITE_BUILD_ENV__, window.__SITE_CONFIG__)
|
||||||
|
|
||||||
document.title = site.title
|
document.title = site.title
|
||||||
for (const [selector, content] of [
|
for (const [selector, content] of [
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { escapeHtml, pickPublicEnv, resolveSiteConfig } from '../src/site-config.js'
|
||||||
|
|
||||||
|
test('defaults preserve the original site and hide unconfigured registrations', () => {
|
||||||
|
const config = resolveSiteConfig({}, {}, 2026)
|
||||||
|
assert.equal(config.projectName, '未完待续')
|
||||||
|
assert.equal(config.copyright, '© 2026 未完待续')
|
||||||
|
assert.equal(config.icpNumber, '')
|
||||||
|
assert.equal(config.publicSecurityNumber, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('runtime overrides build values while keeping unspecified build settings', () => {
|
||||||
|
const config = resolveSiteConfig({
|
||||||
|
VITE_PROJECT_NAME: '构建项目',
|
||||||
|
VITE_PROJECT_NAME_EN: 'BUILD NAME',
|
||||||
|
VITE_ICP_NUMBER: '构建备案号',
|
||||||
|
}, { VITE_PROJECT_NAME: '运行项目' }, 2026)
|
||||||
|
assert.equal(config.projectName, '运行项目')
|
||||||
|
assert.equal(config.projectNameEn, 'BUILD NAME')
|
||||||
|
assert.equal(config.icpNumber, '构建备案号')
|
||||||
|
assert.equal(config.title, '运行项目 · 美好的事,即将发生')
|
||||||
|
assert.equal(config.copyright, '© 2026 运行项目')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('empty runtime values hide optional build content and fall back for required text', () => {
|
||||||
|
const config = resolveSiteConfig({
|
||||||
|
VITE_PROJECT_NAME: '构建项目',
|
||||||
|
VITE_PAGE_TITLE: '构建标题',
|
||||||
|
VITE_ICP_NUMBER: '已有备案号',
|
||||||
|
}, {
|
||||||
|
VITE_PROJECT_NAME: ' ',
|
||||||
|
VITE_PAGE_TITLE: '',
|
||||||
|
VITE_PROJECT_NAME_EN: '',
|
||||||
|
VITE_COPYRIGHT: '',
|
||||||
|
VITE_FOOTER_NOTE: '',
|
||||||
|
VITE_ICP_NUMBER: '',
|
||||||
|
})
|
||||||
|
assert.equal(config.projectName, '未完待续')
|
||||||
|
assert.equal(config.title, '未完待续 · 美好的事,即将发生')
|
||||||
|
for (const key of ['projectNameEn', 'copyright', 'footerNote', 'icpNumber']) {
|
||||||
|
assert.equal(config[key], '')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('copyright substitutes placeholders without interpreting project name as a template', () => {
|
||||||
|
const config = resolveSiteConfig({
|
||||||
|
VITE_PROJECT_NAME: '项目 {year}',
|
||||||
|
VITE_COPYRIGHT: '© {year} {projectName} · 保留所有权利',
|
||||||
|
}, {}, 2030)
|
||||||
|
assert.equal(config.copyright, '© 2030 项目 {year} · 保留所有权利')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('registration URLs allow only HTTP or HTTPS and keep labels for invalid links', () => {
|
||||||
|
const config = resolveSiteConfig({
|
||||||
|
VITE_ICP_NUMBER: '测试备案号',
|
||||||
|
VITE_ICP_URL: 'javascript:alert(1)',
|
||||||
|
VITE_PUBLIC_SECURITY_NUMBER: '测试公安备案号',
|
||||||
|
VITE_PUBLIC_SECURITY_URL: 'https://example.com/registration?id=123',
|
||||||
|
})
|
||||||
|
assert.equal(config.icpNumber, '测试备案号')
|
||||||
|
assert.equal(config.icpUrl, '')
|
||||||
|
assert.equal(config.publicSecurityUrl, 'https://example.com/registration?id=123')
|
||||||
|
assert.equal(resolveSiteConfig({ VITE_ICP_URL: 'data:text/html,test' }).icpUrl, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('only explicitly supported string ENV values are published', () => {
|
||||||
|
const env = Object.assign(Object.create({ VITE_PROJECT_NAME_EN: 'inherited' }), {
|
||||||
|
VITE_PROJECT_NAME: '公开名称',
|
||||||
|
VITE_ICP_NUMBER: '',
|
||||||
|
VITE_COPYRIGHT: null,
|
||||||
|
VITE_OTHER_SECRET: 'do-not-publish',
|
||||||
|
DATABASE_PASSWORD: 'do-not-publish',
|
||||||
|
})
|
||||||
|
assert.deepEqual(pickPublicEnv(env), { VITE_PROJECT_NAME: '公开名称', VITE_ICP_NUMBER: '' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('special characters are escaped and multiline descriptions have plain metadata', () => {
|
||||||
|
assert.equal(escapeHtml(`<script title="'">&</script>`), '<script title="'">&</script>')
|
||||||
|
const config = resolveSiteConfig({ VITE_PROJECT_DESCRIPTION: '第一行\n第二行' })
|
||||||
|
assert.equal(config.description, '第一行\n第二行')
|
||||||
|
assert.equal(config.metaDescription, '第一行 第二行')
|
||||||
|
})
|
||||||
+11
-2
@@ -1,10 +1,12 @@
|
|||||||
import { defineConfig, loadEnv } from 'vite'
|
import { defineConfig, loadEnv } from 'vite'
|
||||||
import { escapeHtml, resolveSiteConfig } from './src/site-config.js'
|
import { escapeHtml, pickPublicEnv, resolveSiteConfig } from './src/site-config.js'
|
||||||
|
|
||||||
export default defineConfig(({ mode }) => {
|
export default defineConfig(({ mode }) => {
|
||||||
const config = resolveSiteConfig(loadEnv(mode, process.cwd(), 'VITE_'))
|
const buildEnv = pickPublicEnv(loadEnv(mode, process.cwd(), 'VITE_'))
|
||||||
|
const config = resolveSiteConfig(buildEnv)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
define: { __SITE_BUILD_ENV__: JSON.stringify(buildEnv) },
|
||||||
plugins: [{
|
plugins: [{
|
||||||
name: 'site-metadata',
|
name: 'site-metadata',
|
||||||
transformIndexHtml: {
|
transformIndexHtml: {
|
||||||
@@ -14,6 +16,13 @@ export default defineConfig(({ mode }) => {
|
|||||||
escapeHtml(key === 'TITLE' ? config.title : config.metaDescription))
|
escapeHtml(key === 'TITLE' ? config.title : config.metaDescription))
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
generateBundle() {
|
||||||
|
this.emitFile({
|
||||||
|
type: 'asset',
|
||||||
|
fileName: 'site-config.build.json',
|
||||||
|
source: JSON.stringify(buildEnv, null, 2),
|
||||||
|
})
|
||||||
|
},
|
||||||
}],
|
}],
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
Reference in new issue
Block a user