Skip to content

Instantly share code, notes, and snippets.

@sumy7
Created November 29, 2023 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumy7/2a1175947d831a4eee9e8cfb2df51686 to your computer and use it in GitHub Desktop.
Save sumy7/2a1175947d831a4eee9e8cfb2df51686 to your computer and use it in GitHub Desktop.
load dotenv and merge into process.env
const dayjs = require('dayjs')
const dotenv = require('dotenv')
const dotenvExpand = require('dotenv-expand')
const path = require('path')
const fs = require('fs')
const today = dayjs()
// 处理默认环境变量
process.env.CI_COMMIT_SHORT_SHA = process.env.CI_COMMIT_SHORT_SHA || '0'
/**
* 加载env文件
* @param mode {string} 环境变量模式
* @param envDir {string} env文件目录
* @param prefixes {undefined | string[]} env变量前缀,只有该前缀的变量才会导出到客户端
*/
function loadEnv(mode, envDir, prefixes) {
if (!prefixes) {
prefixes = ["LB_"];
}
if (mode === "local") {
throw new Error("local mode is not supported");
}
const env = {};
const envFiles = [
".env",
`.env.local`,
`.env.${mode}`,
`.env.${mode}.local`
];
const parsed = Object.fromEntries(
envFiles.flatMap((file) => {
const filePath = path.join(envDir, file);
const fileStat = fs.statSync(filePath, { throwIfNoEntry: false });
if (fileStat && fileStat.isFile()) {
return Object.entries(dotenv.parse(fs.readFileSync(filePath)));
}
return [];
})
);
// 该指令除了处理env中的${}引用,还会将env中的变量注入到process.env中
dotenvExpand.expand({ parsed });
// 检查变量的前缀,只有LB_开头的变量才会导出到客户端
for (const [key, value] of Object.entries(parsed)) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env[key] = value;
}
}
// 检查环境变量中是否还存在LB_开头的变量,如果存在,也导出到客户端
for (const key in process.env) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env[key] = process.env[key];
}
}
return env;
}
module.exports = {
loadEnv,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment