@natoboram/load_env
A standalone implementation of Vite's loadEnv
.
@natoboram/load_env
is available on npmjs, GitHub Packages, and GitHub Releases.
pnpm i @natoboram/load_env
The loadEnv
function loads environment variables from the current directory's .env
files. NODE_ENV
has to be set in the environment and will not be picked up from the filesystem.
If NODE_ENV
is not set, it defaults to development
.
Environment variables are loaded in the following order:
.env.${NODE_ENV}.local
.env.${NODE_ENV}
.env.local
.env
Additional functions are provided for the type safety of environment variables. See the documentation for the full list of available functions.
import {
envBool,
envFloat,
envInt,
envString,
envUrl,
envUuid,
loadEnv,
maybeEnvBool,
maybeEnvFloat,
maybeEnvInt,
maybeEnvString,
maybeEnvUrl,
maybeEnvUuid,
} from "@natoboram/load_env"
import type { UUID } from "crypto"
loadEnv()
export const EXAMPLE_BOOLEAN: boolean = envBool("EXAMPLE_BOOLEAN")
export const EXAMPLE_FLOAT: number = envFloat("EXAMPLE_FLOAT")
export const EXAMPLE_INT: number = envInt("EXAMPLE_INT")
export const EXAMPLE_STRING: string = envString("EXAMPLE_STRING")
export const EXAMPLE_URL: URL = envUrl("EXAMPLE_URL")
export const EXAMPLE_UUID: UUID = envUuid("EXAMPLE_UUID")
export const OPTIONAL_BOOL: boolean | undefined = maybeEnvBool("EXAMPLE_BOOL")
export const OPTIONAL_FLOAT: number | undefined = maybeEnvFloat("EXAMPLE_FLOAT")
export const OPTIONAL_INT: number | undefined = maybeEnvInt("EXAMPLE_INT")
export const OPTIONAL_STR: string | undefined = maybeEnvString("EXAMPLE_STR")
export const OPTIONAL_URL: URL | undefined = maybeEnvUrl("EXAMPLE_URL")
export const OPTIONAL_UUID: UUID | undefined = maybeEnvUuid("EXAMPLE_UUID")
Non-optional functions support a default value as the second argument.
export const EXAMPLE_STRING: string = envString("EXAMPLE_STRING", "default")