UNPKG

dotenv-local

Version:

A utility library for loading local environment variables with prioritized file loading in Node.js and Vite projects. Extends dotenv functionality for better environment management in various modes like development, production, and testing.

53 lines (52 loc) 1.42 kB
// src/index.ts import dotenv from "dotenv"; import path from "path"; var getEnvFilesForMode = (mode) => { return [ `.env`, `.env.local`, `.env.${mode}`, `.env.${mode}.local` ]; }; var loadEnv = (opts = {}) => { const { mode = process.env.NODE_ENV || "production", envDir = process.cwd(), envPrefix = "APP_", envInitial = {}, removeEnvPrefix = false, encoding = "utf-8" } = opts; const envFiles = getEnvFilesForMode(mode); const prefixList = (Array.isArray(envPrefix) ? envPrefix : [envPrefix]).filter((it) => it); if (mode === "local") { throw new Error("The 'local' mode is not allowed."); } if (envPrefix.length === 0) { throw new Error("The 'envPrefix' cannot be an empty string or array."); } const envFileLoad = { ...envInitial }; envFiles.forEach((file) => { const filePath = path.join(envDir, file); dotenv.configDotenv({ path: filePath, override: true, processEnv: envFileLoad, encoding }); }); const envResult = {}; const regExp = removeEnvPrefix ? new RegExp(`^(${prefixList.join("|")})`) : false; Object.entries(envFileLoad).forEach(([key, value]) => { const hasPrefix = prefixList.some((p) => key.startsWith(p)); if (hasPrefix) { const newKey = regExp ? key.replace(regExp, "") : key; envResult[newKey] = value; } }); return envResult; }; export { loadEnv };