当需要测试不同后端环境时,如何基于 `dotenv` 动态注入端点?
解读
国内前端项目普遍采用「本地→测试→预发布→生产」四级流水线,每个阶段对应不同的 GraphQL 网关地址、端口甚至鉴权方式。面试官想知道你是否能把“环境变量”与“Apollo Client 初始化”解耦,做到:
- 不改动业务代码即可切换后端;
- 在 CI/CD 里通过一行命令完成多环境部署;
- 避免把敏感信息(token、数据库连接串)写进仓库。
知识点
- dotenv 加载顺序:
.env→.env.local→.env.[mode]→.env.[mode].local,后加载的覆盖前面的。 - Vite/CRA/Umi 等国内主流脚手架在
import.meta.env或process.env上暴露变量时,只有VITE_*或REACT_APP_*前缀才会被注入。 - Apollo Client 的
HttpLink构造函数只认运行时字符串,构建阶段必须把变量“钉”进去。 - 国内云厂商(阿里云函数计算、腾讯云云开发、Vercel 国内节点)要求在
build.env或tcb env:create里显式声明变量,否则会被裁剪。 - 安全合规:
.env.*.local必须写进.gitignore,防止 staging 的 AK/SK 被推到 Gitee/GitLab 公有库。
答案
步骤一:目录约定
.env # 公共变量,提交仓库
.env.development # 本地联调
.env.staging # 预发布
.env.production # 线上
步骤二:变量命名(以 Vite 为例)
# .env.development
VITE_GRAPHQL_ENDPOINT=https://dev-gateway.company.com/graphql
VITE_GRAPHQL_SUBSCRIPTION=wss://dev-gateway.company.com/graphql
步骤三:创建 src/config/apollo.ts
import { ApolloClient, InMemoryCache, split, HttpLink } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { getMainDefinition } from '@apollo/client/utilities';
const httpLink = new HttpLink({
uri: import.meta.env.VITE_GRAPHQL_ENDPOINT,
credentials: 'include', // 国内常见:带 cookie 鉴权
});
const wsLink = new GraphQLWsLink(
createClient({
url: import.meta.env.VITE_GRAPHQL_SUBSCRIPTION,
connectionParams: () => ({
authorization: localStorage.getItem('token') || '',
}),
})
);
const splitLink = split(
({ query }) => {
const def = getMainDefinition(query);
return def.kind === 'OperationDefinition' && def.operation === 'subscription';
},
wsLink,
httpLink
);
export const apolloClient = new ApolloClient({
link: splitLink,
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
// 国内分页习惯:offset + limit
articles: {
keyArgs: false,
merge(existing = [], incoming) {
return [...existing, ...incoming];
},
},
},
},
},
}),
});
步骤四:package.json 脚本
"scripts": {
"dev": "vite --mode development",
"build:staging": "vite build --mode staging",
"build:prod": "vite build --mode production"
}
步骤五:CI/CD(GitHub Actions 示例,国内 Runner)
- name: Build for staging
run: |
echo "VITE_GRAPHQL_ENDPOINT=${{ secrets.STAGING_ENDPOINT }}" >> .env.staging
yarn build:staging
通过以上五步,本地 yarn dev 自动走 dev 网关,Jenkins/云效流水线只需注入对应变量即可零代码切换后端。
拓展思考
- 如果后端地址在运行时才能拿到(如 SSR 首次请求
/_config),可把HttpLink的 uri 写成函数,动态返回;但注意此时 dotenv 已失效,需要把“环境”与“运行时配置”分层。 - 微前端场景下,子应用可能部署在不同域名,主应用通过
importmaps下发变量,可结合@apollo/client/link/schema做本地缓存兜底,防止子应用重复实例化 Client。 - 国内微信小程序要求 wss 域名提前配置到业务域名白名单,此时
.env里只能写同一条 wss 地址,不同环境通过路径前缀区分,例如wss://gateway.company.com/staging/graphql,避免重新提审。 - 安全加固:把
VITE_GRAPHQL_ENDPOINT放进window.__RUNTIME_CONFIG__,由运维在 Nginx 层注入,实现“同包不同配置”,满足金融类客户“构建包必须可重放”的合规要求。