Examples
env-mage examples
Examples
Practical examples of using env-mage in real-world scenarios.
Project Setup
# Initialize a project with environment variables
echo "DATABASE_URL=postgres://user:pass@localhost:5432/mydb
API_KEY=abc123
DEBUG=true
PORT=3000" > .env
# Create a template file
env-mage initOutput:
✓ Reading source file: .env
✓ Found 4 environment variables
✓ Creating template file: .env.example
✓ Template created successfully!Result (.env.example):
DATABASE_URL=
API_KEY=
DEBUG=
PORT=Environment Validation
# Validate that all required variables are present
env-mage validate --strictOutput (success):
✓ Reading .env file
✓ Reading template file
✓ All required variables are present
✓ No extra variables found
✓ Validation passed!Output (failure):
✓ Reading .env file
✓ Reading template file
✗ Missing variables: REDIS_URL
✗ Validation failed: 1 variable missingTypeScript Integration
# Generate type definitions
env-mage typegen --output src/types/env.d.tsOutput:
✓ Reading environment file: .env
✓ Found 4 environment variables
✓ Inferring variable types
✓ Generating TypeScript definitions
✓ Writing to src/types/env.d.ts
✓ Type definitions created successfully!Usage in code:
// The types are automatically available to TypeScript
const dbUrl = process.env.DATABASE_URL; // string
const port = parseInt(process.env.PORT); // number
const debug = process.env.DEBUG === 'true'; // boolean
// Type errors will be shown:
// process.env.UNDEFINED_VAR // Error: Property doesn't existCI/CD Pipeline
# .github/workflows/validate-env.yml
name: Validate Environment
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- run: npm install -g env-mage
- run: cp .env.ci .env
- run: env-mage validate --strict
- run: env-mage lint