/*
|
* @Description:
|
* @Version: 2.0
|
* @Autor: yuxinqiang
|
* @Date: 2022-09-19 15:24:03
|
* @LastEditors: yuxinqiang
|
* @LastEditTime: 2022-09-19 15:30:36
|
*/
|
/* vite相关 Dotenv 是一个零依赖的模块,它能将环境变量中的变量从 .env 文件加载到 process.env 中
|
使用 dotenv 可以让我们免于在各个文件中引入配置文件,也可以很好的解决敏感信息的泄漏*/
|
import dotenv from 'dotenv'
|
|
export interface ViteEnv {
|
VITE_PORT: number
|
VITE_OPEN: boolean
|
VITE_BASE_PATH: string
|
VITE_OUT_DIR: string
|
VITE_PROXY_URL: string
|
}
|
|
export function isDev(mode: string): boolean {
|
return mode === 'development'
|
}
|
|
export function isProd(mode: string | undefined): boolean {
|
return mode === 'production'
|
}
|
|
// Read all environment variable configuration files to process.env
|
export function loadEnv(mode: string): ViteEnv {
|
const ret: any = {}
|
const envList = [`.env.${mode}.local`, `.env.${mode}`, '.env.local', '.env']
|
envList.forEach((e) => {
|
dotenv.config({ path: e })
|
})
|
for (const envName of Object.keys(process.env)) {
|
let realName = (process.env as any)[envName].replace(/\\n/g, '\n')
|
realName = realName === 'true' ? true : realName === 'false' ? false : realName
|
if (envName === 'VITE_PORT') realName = Number(realName)
|
if (envName === 'VITE_OPEN') realName = Boolean(realName)
|
if (envName === 'VITE_PROXY') {
|
try {
|
realName = JSON.parse(realName)
|
} catch (error) {
|
realName = ''
|
}
|
}
|
ret[envName] = realName
|
if (typeof realName === 'string') {
|
process.env[envName] = realName
|
} else if (typeof realName === 'object') {
|
process.env[envName] = JSON.stringify(realName)
|
}
|
}
|
return ret
|
}
|