Skip to content

在 Vite 构建后自动生成 runtime-config.js 文件

Vite 构建后自动生成一个 runtime-config.js 文件,通过 <script> 标签在 HTML 中引入,并让你的应用在运行时获取这个配置。


✅ 最佳实践方案:生成 runtime-config.js

1. 💡 构建后自动生成 JS 配置文件(非打包进代码)

🚀 目标:

  • .env.production ➜ 编译后变为 dist/runtime-config.js
  • 配置内容通过浏览器运行时全局变量 window.__RUNTIME_CONFIG__ 注入
  • 应用运行时可访问 window.__RUNTIME_CONFIG__.VITE_API_BASE_URL 等变量

🛠 实现步骤

✅ 第一步:添加脚本 generate-runtime-config.js

js
// scripts/generate-runtime-config.js
const fs = require('fs')
const dotenv = require('dotenv')
const path = require('path')

// 读取 .env.production
const env = dotenv.parse(fs.readFileSync(path.resolve(__dirname, '../.env.production')))

const runtimeConfig = {}
for (const key in env) {
  if (key.startsWith('VITE_')) {
    runtimeConfig[key] = env[key]
  }
}

// 输出为 runtime-config.js
const jsContent = `window.__RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig, null, 2)}`
fs.writeFileSync(path.resolve(__dirname, '../dist/runtime-config.js'), jsContent)

console.log('✅ runtime-config.js 生成成功')

✅ 第二步:打包后自动调用该脚本

package.json 添加构建钩子:

json
{
  "scripts": {
    "build": "vite build && node scripts/generate-runtime-config.js"
  }
}

✅ 第三步:在 index.html 引入这个 JS

html
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>My App</title>
    <script src="/runtime-config.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

✅ 第四步:在 app 中使用配置

ts
// src/config/runtime.ts
export const getRuntimeConfig = () => {
  return (window as any).__RUNTIME_CONFIG__ || {}
}
ts
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { getRuntimeConfig } from './config/runtime'

const config = getRuntimeConfig()
console.log('运行时配置:', config)

const app = createApp(App)
app.mount('#app')

✅ 优点

  • 配置文件不打进代码 ✅
  • 可以部署后随时修改配置 ✅
  • JS 格式比 JSON 更灵活 ✅
  • 支持复杂对象、运行时逻辑 ✅

Released under the MIT License.