前端项目在本地开发、测试和生产环境之间切换时,经常需要配置不同的服务地址、功能开关和模块集合。直接在页面中写死环境判断,会让部署与测试越来越难维护。Vite 提供环境模式、构建时变量和模块批量导入能力。本文介绍如何建立明确的配置契约,并验证构建后的实际行为。
1. 先划分公开与私有配置
浏览器能够读取构建后的 JavaScript,因此前端公开配置不能包含数据库密码或私人 API 密钥。环境变量文件只是配置来源,不是安全隔离层。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d3fbbd526808b9378d86a88f1199eafe7e855613">
<section data-environment-panel><h2>运行环境</h2><output data-app-mode></output></section>
</div>
2. 读取 Vite 环境模式
Vite 通过 import.meta.env 暴露模式和构建相关字段。MODE 与 DEV、PROD 并不是同一种概念,不能把任意自定义模式直接等同于生产或开发运行状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/ff3614ed36c1ebaeabd92a47ed560eed4799e07a">
<p>构建模式:<span data-mode></span></p>
</div>
document.querySelector('[data-mode]').textContent = import.meta.env.MODE;
3. 通过环境文件管理公开配置
将 API 基础地址等公开字段按模式配置,默认只有 VITE_ 前缀的自定义环境变量暴露给客户端。部署到不同地址时,应明确是否需要重新构建。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/031fc2b4ebe9e073ea48634b5b568ae45add3205">
<section><h3>服务连接</h3><p data-service-status>等待初始化</p></section>
</div>
# .env.staging 示例
VITE_API_BASE=/staging-api
VITE_ENABLE_REPORTS=true
4. 集中转换字符串配置
自定义环境变量通常是字符串,不能直接使用 Boolean(value) 解析开关,因为字符串 false 仍然为真。建立唯一配置模块并在启动时验证值。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c87f96dedb85b409d95f44c0fadc616b09e44225">
<p data-config-status role="status">检查应用配置</p>
</div>
function readBoolean(value: string | undefined, fallback: boolean) {
if (value === undefined) return fallback;
if (value === 'true') return true;
if (value === 'false') return false;
throw new Error('无效的布尔配置');
}
export const config = Object.freeze({
reports: readBoolean(import.meta.env.VITE_ENABLE_REPORTS, false) });
5. 补充 TypeScript 环境类型
通过声明文件描述应用支持的配置字段,可改善编辑器提示。但类型声明不会检查实际环境文件是否存在,因此运行时验证仍不可省略。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b3b4fcbc146dd1ed3ab4df1254f6c98582be52b3">
<section><h3>功能设置</h3><p data-feature-description></p></section>
</div>
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE?: string;
readonly VITE_ENABLE_REPORTS?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv }
6. 区分开发代理与生产网络配置
Vite 的 dev server proxy 只适用于开发服务器。生产部署需要由实际网关或服务器提供相应路由,不能假设开发代理配置会自动进入构建产物。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
<button type="button" data-check-service>检查接口连接</button><p data-check-result></p>
</div>
// vite.config.ts
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:8080', changeOrigin: true } } } });
7. 使用 import.meta.glob 注册模块
模块数量较多时,可由构建工具生成导入映射,避免为每个配置面板重复编写注册语句。glob 参数应使用构建工具支持的字面量模式。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/742516d897a5e67cb7271a8f575fc6e0fe3056b4">
<label>功能模块 <select data-module-select></select></label><section data-module-host></section>
</div>
const modules = import.meta.glob('./panels/*.ts');
async function loadPanel(key: string) {
const loader = modules[key];
if (!loader) throw new Error('未知模块');
return await loader();
}
8. 明确按需导入与立即导入
默认 glob 导入返回加载函数,模块可按需读取。使用 eager 选项会立即导入匹配模块,更适合体积较小且初始化时必需的配置。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/71a691dfd4be014c98dfd53761b08a06dc9174e9">
<section><h2>已注册功能</h2><ul data-module-list></ul></section>
</div>
const metadata = import.meta.glob('./panels/*.meta.ts', {
eager: true, import: 'default' });
9. 理解构建时替换与运行时配置
静态构建产物中的公开变量通常在构建时确定。若同一产物需要在多个环境运行,可采用受控的运行时公开配置接口,并在应用初始化时校验响应。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6d95e8570561277e9958e2c7218b64646f701ac4">
<p data-bootstrap-state aria-live="polite">正在初始化应用</p>
</div>
async function loadRuntimeConfig() {
const response = await fetch('/runtime-config.json', {
cache: 'no-store' });
if (!response.ok) throw new Error('运行时配置不可用');
return validatePublicConfig(await response.json());
}
10. 检查真正的生产构建
验收不能只依赖开发服务器。分别构建测试模式和生产模式,确认公开配置值、分包结果、资源基础路径和动态模块加载均符合部署约定。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3d3bc9b70970e89a55d9d81e36e7cbadb5ce8a83">
<ul aria-label="构建验收"><li>环境配置正确</li><li>动态模块可以正常加载</li><li>构建产物不包含私有凭据</li></ul>
</div>
npm run build -- --mode staging
npm run build -- --mode production
总结
Vite 工程化配置的重点在于明确配置来源、运行时边界和模块加载方式。集中解析公开环境变量,避免将私人数据打包到浏览器,并对真实构建产物进行测试,才能减少跨环境部署问题。