diff --git a/src/index.ts b/src/index.ts index df36fac..36a72cb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ export * from './config' export { createServer } from './server' export { build } from './build' export { preview } from './preview' +export { loadEnv } from './utils' export * from './plugins/bytecode' export * from './plugins/externalizeDeps' export * from './plugins/swc' diff --git a/src/utils.ts b/src/utils.ts index 5e2037f..41fafc5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,5 @@ import { URL, URLSearchParams } from 'node:url' +import { loadEnv as viteLoadEnv } from 'vite' export function isObject(value: unknown): value is Record { return Object.prototype.toString.call(value) === '[object Object]' @@ -24,3 +25,16 @@ export function parseRequest(id: string): Record | null { } return Object.fromEntries(new URLSearchParams(search)) } + +/** + * Load `.env` files within the `envDir`(default: `process.cwd()`). + * By default, only env variables prefixed with `MAIN_VITE_`, `PRELOAD_VITE_` and + * `RENDERER_VITE_` are loaded, unless `prefixes` is changed. + */ +export function loadEnv( + mode: string, + envDir: string = process.cwd(), + prefixes: string | string[] = ['MAIN_VITE_', 'PRELOAD_VITE_', 'RENDERER_VITE_'] +): Record { + return viteLoadEnv(mode, envDir, prefixes) +}