or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-interface.mdcore-execution.mdenvironment-loading.mdfile-formats.mdindex.mdutilities.md
tile.json

environment-loading.mddocs/

Environment Variable Loading

Environment variable loading system that supports multiple file formats, fallback strategies, and comprehensive error handling. This system forms the core of env-cmd's file processing capabilities.

Capabilities

Main Environment Loading Function

Primary function for loading environment variables from files with automatic format detection and fallback support.

/**
 * Load environment variables from files with support for both env files and RC files
 * @param options - Configuration for loading environment variables
 * @returns Promise resolving to loaded environment variables
 */
function getEnvVars(options?: GetEnvVarOptions): Promise<Environment>;

interface GetEnvVarOptions {
  /** Configuration for .env file loading */
  envFile?: EnvFileOptions;
  /** Configuration for .env-cmdrc file loading */
  rc?: RCFileOptions;
  /** Enable verbose logging output */
  verbose?: boolean;
}

interface EnvFileOptions {
  /** Path to the environment file */
  filePath?: string;
  /** Whether to fall back to default locations if specified file not found */
  fallback?: boolean;
}

interface RCFileOptions {
  /** List of environment names to extract from RC file */
  environments: string[];
  /** Path to the RC file */
  filePath?: string;
}

Usage Examples:

// Via main package (GetEnvVars is an alias for getEnvVars)
import { GetEnvVars } from "env-cmd";

// Or via direct submodule import
import { getEnvVars } from "env-cmd/dist/get-env-vars.js";

// Load from default .env file locations (using GetEnvVars alias)
const env = await GetEnvVars();

// Load from specific env file
const env = await GetEnvVars({
  envFile: { filePath: ".env.production" },
  verbose: true
});

// Load from RC file with specific environments
const env = await GetEnvVars({
  rc: {
    environments: ["development", "staging"],
    filePath: ".env-cmdrc"
  }
});

// Load with fallback enabled
const env = await GetEnvVars({
  envFile: {
    filePath: "./config/.env",
    fallback: true
  }
});

Environment File Loading

Function specifically for loading standard environment files (.env, .env.json, .env.js, etc.).

/**
 * Load environment variables from .env format files
 * @param options - Configuration for env file loading
 * @returns Promise resolving to environment variables
 */
function getEnvFile(
  { filePath, fallback, verbose }: { filePath?: string, fallback?: boolean, verbose?: boolean },
): Promise<Environment>;

Default File Locations:

  • ./.env
  • ./.env.js
  • ./.env.json

File Resolution Process:

  1. If filePath specified, try to load from that path
  2. If loading fails and fallback is true, try default locations
  3. If fallback is false, throw error for missing specified file
  4. Try each default location in order until one succeeds

RC File Loading

Function for loading multi-environment configuration files (.env-cmdrc format).

/**
 * Load environment variables from .env-cmdrc format files
 * @param options - Configuration for RC file loading
 * @returns Promise resolving to environment variables
 */
function getRCFile(
  { environments, filePath, verbose }: { environments: string[], filePath?: string, verbose?: boolean },
): Promise<Environment>;

Default RC File Locations:

  • ./.env-cmdrc
  • ./.env-cmdrc.js
  • ./.env-cmdrc.json

RC File Format:

{
  "development": {
    "NODE_ENV": "development",
    "API_URL": "http://localhost:3000"
  },
  "production": {
    "NODE_ENV": "production", 
    "API_URL": "https://api.production.com"
  }
}

Low-Level File Parsing Functions

Direct file parsing functions for specific file formats.

/**
 * Parse environment variables from a specific file path
 * @param envFilePath - Path to the environment file
 * @returns Promise resolving to parsed environment variables
 */
function getEnvFileVars(envFilePath: string): Promise<Environment>;

/**
 * Parse environment variables from RC file with specific environments
 * @param options - RC file configuration
 * @returns Promise resolving to merged environment variables
 */
function getRCFileVars(
  { environments, filePath }: { environments: string[], filePath: string },
): Promise<Environment>;

Supported File Extensions

The environment loading system supports the following file extensions:

const IMPORT_HOOK_EXTENSIONS = [
  '.json',
  '.js',
  '.cjs',
  '.mjs',
  '.ts',
  '.mts',
  '.cts',
  '.tsx',
];

File Type Handling:

  • .env: Parsed as dotenv format (key=value pairs)
  • .json: Imported as JSON with type assertion
  • .js/.mjs/.cjs: Dynamically imported as ES/CommonJS modules
  • .ts/.mts/.cts: TypeScript modules (requires tsx loader support)

Error Handling

The loading system provides comprehensive error handling with specific error types:

Error Types

interface PathError extends Error {
  name: 'PathError';
}

interface EnvironmentError extends Error {
  name: 'EnvironmentError';
}

interface ParseError extends Error {
  name: 'ParseError';
}

Error Scenarios

PathError: Thrown when files cannot be found

// File not found at specified path
const pathError = new Error(`Invalid env file path (${envFilePath}).`);
pathError.name = 'PathError';
throw pathError;

EnvironmentError: Thrown when specified environments don't exist in RC files

// Environment not found in RC file
const envError = new Error(`Failed to find environments: [${environments.join(',')}]`);
envError.name = 'EnvironmentError';
throw envError;

ParseError: Thrown when file parsing fails

// File exists but cannot be parsed
const parseError = new Error(`Failed to parse file: ${filePath}`);
parseError.name = 'ParseError';
throw parseError;

Verbose Logging

When verbose mode is enabled, the loading system provides detailed logging:

// Success messages
console.info(`Found .env file at path: ${filePath}`);
console.info(`Found environments: [${environments.join(',')}] for .rc file at path: ${filePath}`);

// Failure messages  
console.info(`Failed to find .env file at path: ${filePath}`);
console.info(`Failed to find environments: [${environments.join(',')}] for .rc file at path: ${filePath}`);

File Resolution

Path resolution includes home directory expansion and absolute path conversion:

/**
 * Resolve file paths with home directory expansion
 * @param userPath - User-provided file path (may include ~)
 * @returns Absolute resolved path
 */
function resolveEnvFilePath(userPath: string): string;

Resolution Features:

  • Home directory expansion: ~/config/.env/home/user/config/.env
  • Relative path resolution: ./config/.env/current/dir/config/.env
  • Absolute path passthrough: /absolute/path/.env/absolute/path/.env