UNPKG

@hairy/lnv

Version:

Loading environment variables in Next.js and other frameworks can be quite cumbersome, and using dotenv or vault at runtime is also inconvenient. That's why my created this tool

44 lines (41 loc) 1.3 kB
import {createRequire as __createRequire} from 'module';var require=__createRequire(import.meta.url); // src/write.ts import fs from "node:fs"; import path from "node:path"; import process from "node:process"; function write(filepath, parsed = {}) { const contents = Object.entries(parsed).map(([key, value]) => `${key}=${value}`); const content = [ "# This file is generated by lnv command", "# DO NOT ATTEMPT TO EDIT THIS FILE", contents.join("\n") ].join("\n"); fs.writeFileSync(filepath, content, "utf-8"); } function writeDts(filepath, parsed = {}) { const resolvedFilepath = path.isAbsolute(filepath) ? filepath : path.join(process.cwd(), filepath); fs.mkdirSync(path.dirname(resolvedFilepath), { recursive: true }); function normalizeKey(key) { if (/^[A-Z_$]\w*$/i.test(key)) return key; return `'${key.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`; } const contents = Object.keys(parsed).sort().map((key) => ` ${normalizeKey(key)}?: string`); const content = [ "declare global {", " namespace NodeJS {", " interface ProcessEnv {", ...contents, " }", " }", "}", "", "export {}", "" ].join("\n"); fs.writeFileSync(resolvedFilepath, content, "utf-8"); } export { write, writeDts };