env 按当前平台与模式提前加载环境变量,并生成类型声明文件。
配置
unh.config.ts
import { defineConfig } from '@uni-helper/unh'
export default defineConfig({
// 用默认配置开启
env: true,
})
unh.config.ts
import { defineConfig } from '@uni-helper/unh'
export default defineConfig({
env: {
root: 'envs',
usePlatformDir: true,
prefixes: ['VITE_', 'UNI_'],
intoProcess: true,
dts: 'uni-env.d.ts',
},
})
加载哪些文件
unh 按以下顺序读取文件,后读的覆盖先读的:
.env.env.local.env.{mode}.env.{mode}.local
usePlatformDir 为 true 时,文件放在平台名子目录下。例如 root 为 envs 时,路径是 envs/mp-weixin/.env、envs/h5/.env。
只有匹配 prefixes 的变量会被加载。
配置项
env
env
true | EnvConfig
true 用默认配置开启,对象形式逐项配置。root
root
string
环境变量文件的根目录。
usePlatformDir
usePlatformDir
boolean
是否用平台名当子目录。
prefixes
prefixes
string[]
只加载这些前缀开头的变量。
intoProcess
intoProcess
boolean
是否把加载的变量合并进
process.env。dts
dts
false | string
类型声明文件的路径。
false 不生成。生成类型声明
dts 不为 false 时,unh 生成一个声明文件,内容形如:
uni-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
/** 环境变量 */
readonly VITE_API_BASE_URL: string;
}
变量名来自实际加载到的环境变量,不要手改这个文件。
示例
按平台放不同的接口地址:
envs/
h5/.env
mp-weixin/.env
envs/mp-weixin/.env
VITE_API_BASE_URL=https://mp.example.com
unh.config.ts
import { defineConfig } from '@uni-helper/unh'
export default defineConfig({
env: {
root: 'envs',
usePlatformDir: true,
},
})