dotenv-type-generator
v1.0.0
Published
Reads .env files and auto-generates TypeScript ProcessEnv type declarations
Maintainers
Readme
dotenv-type-generator
Reads a .env file and auto-generates TypeScript ProcessEnv type declarations — zero config, zero annotations required.
Install
npm install -D dotenv-type-generatorUsage
# Generate env.d.ts from .env (default)
npx dotenv-type-generator
# Custom .env path
npx dotenv-type-generator .env.local
# Write to a custom output file
npx dotenv-type-generator .env --out src/types/env.d.ts
# Generate a Zod validation schema instead
npx dotenv-type-generator .env --zod --out src/env.ts
# Print to stdout
npx dotenv-type-generator .env --printWhat it generates
Given a .env file:
# Database configuration
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
PORT=3000
JWT_SECRET=super-secret-key
[email protected]It generates env.d.ts:
// Auto-generated by dotenv-type-generator. Do not edit manually.
declare namespace NodeJS {
interface ProcessEnv {
/** Database configuration */
DATABASE_URL: string;
PORT: string;
JWT_SECRET: string;
SUPPORT_EMAIL: string;
}
}Now process.env.DATABASE_URL is fully typed. Typos in variable names are caught at compile time.
Zod schema output
With --zod, generates a Zod validation schema that validates env vars at startup:
import { z } from 'zod';
export const envSchema = z.object({
DATABASE_URL: z.string().url(),
PORT: z.string(),
JWT_SECRET: z.string(),
SUPPORT_EMAIL: z.string().email(),
});
export type Env = z.infer<typeof envSchema>;Auto-run on install
Add to your package.json to auto-generate on every install:
{
"scripts": {
"postinstall": "dotenv-type-generator"
}
}Use as a library
import { parseEnvFile, generateDeclaration, generateZodSchema } from 'dotenv-type-generator';
import { readFileSync } from 'fs';
const content = readFileSync('.env', 'utf8');
const entries = parseEnvFile(content);
const declaration = generateDeclaration(entries);Options
| Flag | Description |
|------|-------------|
| --out <file> | Output file path |
| --zod | Generate Zod schema instead of .d.ts |
| --print | Print to stdout |
