使用 zod 对.env 文件约束

使用 zod 对.env 文件约束

为你的项目安装 zod

bash
pnpm i zod

创建 env.ts

vue 项目中使用

提醒

我这里的 toast 是使用 shadcn-vue 组件库的提示插件,如果您的项目中使用其他的组件库,可以替换为您使用的组件库的提示插件。它只是为了全局提醒您的 env 变量某些部分与规定的类型不一致。

utils/env.tsts
import { h } from 'vue'
import { z } from 'zod'

import { toast } from '@/components/ui/toast'

/**
 * Load .env file and validate it against the schema
 * Has this file, it will be loaded automatically by vite and we will be have environment variables available type
 * If EnvSchema Object has Key but not in .env file, it will be have a error in page
 */

const EnvSchema = z.object({
    // Add your environment variables here, for example:
    VITE_API_BASE_URL: z.string().url(),
})

export type env = z.infer<typeof EnvSchema>

const { data: env, error } = EnvSchema.safeParse(import.meta.env)

if (error) {
    console.error('❌ Invalid env')
    console.error(error.flatten().fieldErrors)
    toast({
        title: `Env error: you should check your .env file`,
        variant: 'destructive',
        description: h('pre', { class: 'mt-2 w-[340px] rounded-md bg-slate-950 p-4' }, h('code', { class: 'text-white' }, JSON.stringify(error, null, 2))),
    })
}

export default env!

在 vue 入口文件引入它

main.tsts
import '@/utils/env'

有了这个文件后,如果您的环境变量中没有 VITE_API_BASE_URL,就会全局提示一个错误,提醒您配置对应的环境变量。

node项目中使用

当然,它也可以运行至node 项目中,且可以在 env 变量与规定不一致时,退出程序

使用技巧

提醒
  • 我们可以使用 .default() 来给它一个默认值,如 NODE_ENV: z.string().default("development"), 就是在 NODE_ENV 没有设置时设置为 development
  • 在 node 端,使用 process.exit(1) 会在必填的环境变量没有时退出

视频版本

Git 提交规范及其在项目里的使用
从本地到生产:使用 Docker 部署 Nuxt