UNPKG

unplugin-typedotenv

Version:

typedotenv plugin for webpack/vite (dotenv utility for TypeScript)

51 lines (49 loc) 1.32 kB
// src/index.ts import * as path from "path"; import { generate } from "@typedotenv/core"; import * as fs from "fs/promises"; import { createUnplugin } from "unplugin"; var resolveDotenv = ({ env, envDir, envFile }) => { if (envFile) return envFile; const dir = envDir ?? process.cwd(); const file = env ? `.env.${env}` : ".env"; return path.join(dir, file); }; var name = "unplugin-typedotenv"; var src_default = createUnplugin((options) => { const envfile = resolveDotenv(options); const { output = "env.ts" } = options; const generateCode = async () => { try { const [dotenv, previous] = await Promise.all([ fs.readFile(envfile, "utf8"), fs.readFile(output, "utf8").catch(() => { }) ]); const code = generate(dotenv, options); if ((previous == null ? void 0 : previous.replace(/[ \n\r\t]+/g, " ")) !== code.replace(/[ \n\r\t]+/g, " ")) { await fs.writeFile(output, code); } return { code }; } catch (e) { console.error(`[${name}]`, e); return null; } }; return { name, async buildStart() { this.addWatchFile(envfile); await generateCode(); }, async watchChange(id) { if (id !== envfile) return; await generateCode(); } }; }); export { src_default };