UNPKG

env-type-defs

Version:

Automatically generate TypeScript type definitions for environment variables based on the content of your env files.

39 lines (35 loc) 1.21 kB
import { DIRECTORY_PATH, ENV_TYPE_PATH } from "../config"; import { getEnvPath } from "./paths"; import dotenv from "dotenv"; import path from "path"; import fs from "fs"; import { determineType } from "./determine-type"; type envT = { [key: string]: string; }; const envs: envT = {}; export const generateEnvTypes = (pathArg?: string) => { const envFiles = getEnvPath(); envFiles.forEach((env) => { const envPath = pathArg || path.join(DIRECTORY_PATH, env); const envConfig = dotenv.parse(fs.readFileSync(envPath)); Object.keys(envConfig).forEach((key: string) => { envs[key] = determineType(envConfig[key]); }); }); const envPathName = path.join(DIRECTORY_PATH, ENV_TYPE_PATH); let envObject = ""; const envObjKeys = Object.keys(envs); envObjKeys.forEach((key, index) => { envObject += "\t" + key + ":" + envs[key]; if (index != envObjKeys.length - 1) { envObject += ",\n\t"; } }); fs.writeFileSync( envPathName, `// generated by env-type-defs https://www.npmjs.com/package/env-type-defs\ndeclare global {\n namespace NodeJS {\n interface ProcessEnv {\n ${envObject}\n }\n }\n}\nexport {};\n `, {} ); return envs; };