feat: specify env prefixes for vite's loadEnv and export it

This commit is contained in:
alex8088 2022-12-04 01:59:03 +08:00
parent ffb2426e75
commit 16d9932bac
2 changed files with 15 additions and 0 deletions

View file

@ -3,6 +3,7 @@ export * from './config'
export { createServer } from './server' export { createServer } from './server'
export { build } from './build' export { build } from './build'
export { preview } from './preview' export { preview } from './preview'
export { loadEnv } from './utils'
export * from './plugins/bytecode' export * from './plugins/bytecode'
export * from './plugins/externalizeDeps' export * from './plugins/externalizeDeps'
export * from './plugins/swc' export * from './plugins/swc'

View file

@ -1,4 +1,5 @@
import { URL, URLSearchParams } from 'node:url' import { URL, URLSearchParams } from 'node:url'
import { loadEnv as viteLoadEnv } from 'vite'
export function isObject(value: unknown): value is Record<string, unknown> { export function isObject(value: unknown): value is Record<string, unknown> {
return Object.prototype.toString.call(value) === '[object Object]' return Object.prototype.toString.call(value) === '[object Object]'
@ -24,3 +25,16 @@ export function parseRequest(id: string): Record<string, string> | null {
} }
return Object.fromEntries(new URLSearchParams(search)) 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<string, string> {
return viteLoadEnv(mode, envDir, prefixes)
}