zod-env 中文文档教程
Zod-Env
一个简单的库,用于使用 Zod 解析环境变量
安装
npm install zod-env
** 确保也安装了 zod **
npm install zod
基本用法
import { z } from "zod";
import {ZodEnv, booleanAsString} from "zod-env";
const zodEnv = new ZodEnv({
PORT: z.coerce.number().default(3000),
NODE_ENV: z.string().default("development"),
IS_PRODUCTION: booleanAsString().default(false),
});
zodEnv.get("PORT"); // 3000
zodEnv.get("NODE_ENV"); // "development"
zodEnv.get("IS_PRODUCTION"); // false
使用默认值
import { z } from "zod";
import {ZodEnv, booleanAsString} from "zod-env";
const zodEnv = new ZodEnv({
PORT: z.coerce.number().optional(),
NODE_ENV: z.string().optional(),
IS_PRODUCTION: booleanAsString().default(false),
});
zodEnv.get("PORT", "3000"); // 3000
zodEnv.get("NODE_ENV", "development"); // "development"
zodEnv.get("IS_PRODUCTION"); // false
使用自定义环境变量
如果您的环境变量不在默认位置,您可以将自定义对象传递给构造函数。
import { z } from "zod";
import {ZodEnv, booleanAsString} from "zod-env";
const envs = window.__envs__ // or whatever your custom object is
const zodEnv = new ZodEnv({
PORT: z.coerce.number().optional(),
NODE_ENV: z.string().optional(),
IS_PRODUCTION: booleanAsString().default(false),
}, envs);
Zod-Env
A simple library for parsing environment variables using Zod
Installation
npm install zod-env
** Make sure to install zod as well **
npm install zod
Basic Usage
import { z } from "zod";
import {ZodEnv, booleanAsString} from "zod-env";
const zodEnv = new ZodEnv({
PORT: z.coerce.number().default(3000),
NODE_ENV: z.string().default("development"),
IS_PRODUCTION: booleanAsString().default(false),
});
zodEnv.get("PORT"); // 3000
zodEnv.get("NODE_ENV"); // "development"
zodEnv.get("IS_PRODUCTION"); // false
Usage with default values
import { z } from "zod";
import {ZodEnv, booleanAsString} from "zod-env";
const zodEnv = new ZodEnv({
PORT: z.coerce.number().optional(),
NODE_ENV: z.string().optional(),
IS_PRODUCTION: booleanAsString().default(false),
});
zodEnv.get("PORT", "3000"); // 3000
zodEnv.get("NODE_ENV", "development"); // "development"
zodEnv.get("IS_PRODUCTION"); // false
Usage with custom environment variables
If your environemnt variables are not in the default location, you can pass in a custom object to the constructor.
import { z } from "zod";
import {ZodEnv, booleanAsString} from "zod-env";
const envs = window.__envs__ // or whatever your custom object is
const zodEnv = new ZodEnv({
PORT: z.coerce.number().optional(),
NODE_ENV: z.string().optional(),
IS_PRODUCTION: booleanAsString().default(false),
}, envs);