Comprehensive support for multiple environment file formats including standard .env files, JSON configuration, JavaScript modules, TypeScript files, and multi-environment RC files. Each format provides specific advantages for different use cases.
Core function for parsing individual environment files with automatic format detection.
/**
* Gets the environment vars from an env file
* @param envFilePath - Path to the environment file
* @returns Promise resolving to parsed environment variables
*/
function getEnvFileVars(envFilePath: string): Promise<Environment>;Supported Extensions:
const IMPORT_HOOK_EXTENSIONS = [
'.json',
'.js',
'.cjs',
'.mjs',
'.ts',
'.mts',
'.cts',
'.tsx',
];Function for parsing multi-environment configuration files.
/**
* Gets the env vars from the rc file and rc environments
* @param options - RC file configuration with environments
* @returns Promise resolving to merged environment variables
*/
function getRCFileVars(
{ environments, filePath }: { environments: string[], filePath: string },
): Promise<Environment>;Traditional dotenv format with key=value pairs and comment support.
Format:
# This is a comment
NODE_ENV=development
API_URL=http://localhost:3000
DATABASE_URL=postgresql://user:pass@localhost/db
# Multiline values with quotes
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQ..."
# Variable references (processed with --recursive)
FULL_URL=$API_URL/api/v1Features:
#JSON format for structured environment configuration.
Format (.env.json):
{
"NODE_ENV": "development",
"API_URL": "http://localhost:3000",
"DATABASE_URL": "postgresql://user:pass@localhost/db",
"PORT": "3000",
"FEATURE_FLAGS": "{\"newUI\": true, \"beta\": false}"
}Features:
JavaScript modules that export environment objects.
Format (.env.js, .env.mjs, .env.cjs):
// .env.js - ES Module
export default {
NODE_ENV: 'development',
API_URL: process.env.NODE_ENV === 'production'
? 'https://api.production.com'
: 'http://localhost:3000',
BUILD_TIME: new Date().toISOString(),
VERSION: require('./package.json').version
};
// .env.cjs - CommonJS
module.exports = {
NODE_ENV: 'development',
API_URL: 'http://localhost:3000'
};Features:
TypeScript modules with type safety for environment configuration.
Format (.env.ts, .env.mts, .env.cts):
interface EnvironmentConfig {
NODE_ENV: 'development' | 'production' | 'test';
API_URL: string;
PORT: string;
DATABASE_URL: string;
}
const config: EnvironmentConfig = {
NODE_ENV: 'development',
API_URL: 'http://localhost:3000',
PORT: '3000',
DATABASE_URL: 'postgresql://localhost/myapp_dev'
};
export default config;Features:
Multi-environment configuration files supporting environment-specific settings.
Format (.env-cmdrc, .env-cmdrc.json):
{
"development": {
"NODE_ENV": "development",
"API_URL": "http://localhost:3000",
"DEBUG": "true"
},
"staging": {
"NODE_ENV": "staging",
"API_URL": "https://api-staging.example.com",
"DEBUG": "false"
},
"production": {
"NODE_ENV": "production",
"API_URL": "https://api.example.com",
"DEBUG": "false"
}
}JavaScript RC Format (.env-cmdrc.js):
const environments = {
development: {
NODE_ENV: 'development',
API_URL: 'http://localhost:3000'
},
production: {
NODE_ENV: 'production',
API_URL: 'https://api.example.com'
}
};
export default environments;Features:
Files are processed based on their extension:
const ext = extname(absolutePath).toLowerCase();
if (IMPORT_HOOK_EXTENSIONS.includes(ext)) {
// Dynamic import for JS/TS/JSON files
const res = await import(pathToFileURL(absolutePath).href);
return res.default || res;
} else {
// Parse as .env format
return parseEnvFile(absolutePath);
}Different import strategies based on file type:
JSON Files:
const attributeTypes = ext === '.json'
? { with: { type: 'json' } }
: {};
const res = await import(pathToFileURL(absolutePath).href, attributeTypes);TypeScript Files:
if (/tsx?$/.test(ext)) {
checkIfTypescriptSupported(); // Validates tsx loader availability
}Module Resolution:
// Handle both default and named exports
const env = res.default || res;
// Support for promise-returning modules
if (isPromise(env)) {
return await env;
}PathError: File not found or inaccessible
if (!existsSync(absolutePath)) {
const pathError = new Error(`Invalid env file path (${envFilePath}).`);
pathError.name = 'PathError';
throw pathError;
}ParseError: File parsing failures
try {
const parsedVars = parseEnvFormat(content);
return parsedVars;
} catch (e) {
const parseError = new Error(`Failed to parse env file: ${e.message}`);
parseError.name = 'ParseError';
throw parseError;
}LoaderError: Module loading failures
function isLoaderError(error: unknown): error is Error {
return (
error instanceof Error &&
'code' in error &&
error.code === 'ERR_UNKNOWN_FILE_EXTENSION'
);
}EnvironmentError: Requested environment not found in RC file
const envError = new Error(`Failed to find environment "${environment}" in RC file`);
envError.name = 'EnvironmentError';
throw envError;For TypeScript file support, env-cmd checks for tsx loader availability:
/**
* Check if TypeScript is supported in the current environment
* @throws Error if TypeScript files cannot be loaded
*/
function checkIfTypescriptSupported(): void;Loader Detection:
Direct parsing functions for working with environment file content at a granular level.
/**
* Parse out all env vars from a given env file string and return an object
* @param envFileString - Raw environment file content
* @returns Parsed environment variables object
*/
function parseEnvString(envFileString: string): Environment;
/**
* Parse out all env vars from an env file string
* @param envString - Environment string content
* @returns Environment variables object
*/
function parseEnvVars(envString: string): Environment;
/**
* Strips out comments from env file string
* @param envString - Environment file content with comments
* @returns Content with comments removed
*/
function stripComments(envString: string): string;
/**
* Strips out newlines from env file string
* @param envString - Environment file content with empty lines
* @returns Content with empty lines removed
*/
function stripEmptyLines(envString: string): string;
/**
* Normalize imported objects to environment variable format
* @param input - Raw imported object from JS/TS modules
* @param absolutePath - File path for error reporting
* @returns Normalized environment variables with string values
*/
function normalizeEnvObject(input: unknown, absolutePath: string): Environment;Usage Examples:
import { parseEnvString, stripComments } from "env-cmd/dist/parse-env-file.js";
// Parse raw .env content
const envContent = `
# Database configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp
`;
const parsed = parseEnvString(envContent);
// Result: { DB_HOST: 'localhost', DB_PORT: '5432', DB_NAME: 'myapp' }
// Remove comments from content
const cleaned = stripComments(envContent);
// Result: Content without comment linesParsing Process:
stripComments() removes lines starting with #stripEmptyLines() removes blank linesparseEnvVars() extracts key=value pairsFunction for validating TypeScript file loading support in the current environment.
/**
* Check if TypeScript is supported in the current environment
* @throws Error if TypeScript files cannot be loaded
*/
function checkIfTypescriptSupported(): void;Usage:
import { checkIfTypescriptSupported } from "env-cmd/dist/loaders/typescript.js";
try {
checkIfTypescriptSupported();
// TypeScript files can be loaded
} catch (error) {
console.error("TypeScript support not available:", error.message);
}Validation Process:
All file paths undergo resolution processing:
/**
* A simple function for resolving the path the user entered
* @param userPath - User-provided file path
* @returns Absolute resolved path
*/
function resolveEnvFilePath(userPath: string): string;Resolution Features:
~/.env → /home/user/.env./config/.env → /current/dir/config/.envconfig/.env → /current/dir/config/.env