Skip to content

Commit 6dd3731

Browse files
committed
chore: update readme
1 parent a6e632f commit 6dd3731

File tree

1 file changed

+97
-146
lines changed

1 file changed

+97
-146
lines changed

README.md

Lines changed: 97 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,41 @@
22
<img src="https://user-images.githubusercontent.com/8337858/188329992-e74b3393-5bec-48b3-bba9-a8c45d279866.png">
33
</p>
44

5-
This Vite plugin allows you to validate your environment variables at build or dev time. This allows your build/dev-server to [fail-fast](https://en.wikipedia.org/wiki/Fail-fast) if your setup is misconfigured.
5+
# vite-plugin-validate-env
66

7-
No more CI to restart because you are missing an environment variable, or to realize after 10 minutes of debugging that you forgot a variable 🥲
7+
A Vite plugin that validates your environment variables at **build** or **dev time**. This helps you catch misconfigurations early by [failing fast](https://en.wikipedia.org/wiki/Fail-fast). No more broken builds or 10 minutes of debugging just to realize you forgot a variable 🥲
88

9-
## Features
10-
- Validate your environment variables at **build time only**. No runtime overhead
11-
- Totally type-safe
12-
- Support [standard-schema](https://github.com/standard-schema/standard-schema), meaning you can use every libraries compatible with it ( Zod, Valibot, ArkType... )
13-
- Parsing, validation and transformation of your variables
14-
- Custom rules and error messages
9+
---
10+
11+
## ✅ Features
12+
13+
* Validate environment variables **at build time only**, zero runtime overhead
14+
* Fully **type-safe**
15+
* Supports [standard-schema](https://github.com/standard-schema/standard-schema) — works with Zod, Valibot, ArkType, and more
16+
* Built-in parsing, validation, and transformation
17+
* Custom rules and error messages
18+
19+
---
1520

1621
## Installation
1722

1823
```sh
1924
pnpm add -D @julr/vite-plugin-validate-env
2025
```
2126

22-
## Usage
23-
`vite-plugin-validate-env` plugin allows you to validate your env, either with a very simplified builtin validation lib, or with Zod in the most complex cases when you want a very strict validation.
27+
## Basic Usage
28+
29+
You can use the plugin with the [built-in validator](https://github.com/poppinss/validator-lite) for simple use cases, or with libraries like Zod for more advanced schemas.
30+
31+
> [!TIP]
32+
> I would recommend using a dedicated `env.ts` file to keep your Vite config clean and separate from your environment variable definitions. See the [Using a Dedicated `env.ts` Config File](#using-a-dedicated-envts-config-file) section for more details.
33+
34+
### Built-in Validator
2435

25-
### Plugin options
26-
The easiest way to define the options is to directly define the scheme as follows:
2736
```ts
2837
// vite.config.ts
29-
import { defineConfig } from "vite";
30-
import { Schema, ValidateEnv } from "@julr/vite-plugin-validate-env";
38+
import { defineConfig } from 'vite'
39+
import { Schema, ValidateEnv } from '@julr/vite-plugin-validate-env'
3140

3241
export default defineConfig({
3342
plugins: [
@@ -38,16 +47,19 @@ export default defineConfig({
3847
})
3948
```
4049

41-
In case you want to change some plugin options, in particular change the validator (for Zod), you have to set your options as follows:
50+
### Standard Schema Validators
51+
52+
If you want to use Zod or another validator compatible with [standard-schema](https://github.com/standard-schema/standard-schema), pass the `validator` and `schema` manually:
53+
4254
```ts
43-
import { defineConfig } from "vite";
55+
import { defineConfig } from 'vite'
4456
import { z } from 'zod'
45-
import { ValidateEnv } from "@julr/vite-plugin-validate-env";
57+
import { ValidateEnv } from '@julr/vite-plugin-validate-env'
4658

4759
export default defineConfig({
4860
plugins: [
4961
ValidateEnv({
50-
standard,
62+
validator: 'standard', // 👈
5163
schema: {
5264
VITE_MY_VAR: z.string()
5365
}
@@ -56,69 +68,38 @@ export default defineConfig({
5668
})
5769
```
5870

59-
If you want to see what values are being evaluated for the build, for example when running in CI. You can pass the `debug` option as follows:
71+
## Built-in Validator Examples
72+
6073
```ts
61-
import { defineConfig } from "vite";
62-
import { Schema, ValidateEnv } from "@julr/vite-plugin-validate-env";
74+
ValidateEnv({
75+
VITE_STRING: Schema.string(),
76+
VITE_NUMBER: Schema.number(),
77+
VITE_BOOLEAN: Schema.boolean(),
78+
VITE_ENUM: Schema.enum(['foo', 'bar'] as const),
6379

64-
export default defineConfig({
65-
plugins: [
66-
ValidateEnv({
67-
debug: true,
68-
schema: {
69-
VITE_MY_VAR: Schema.string()
70-
}
71-
}),
72-
],
73-
})
74-
```
80+
// Optional
81+
VITE_OPTIONAL: Schema.boolean.optional(),
7582

76-
### Built-in validator
83+
// With format and protocol checks
84+
VITE_API_URL: Schema.string({ format: 'url', protocol: true }),
7785

78-
```ts
79-
import { Schema, ValidateEnv } from "@julr/vite-plugin-validate-env"
80-
import { defineConfig } from "vite";
86+
// With custom error message
87+
VITE_PORT: Schema.number({ message: 'You must set a port!' }),
8188

82-
export default defineConfig({
83-
plugins: [
84-
ValidateEnv({
85-
// Data types
86-
VITE_STRING_VARIABLE: Schema.string(),
87-
VITE_BOOLEAN_VARIABLE: Schema.boolean(),
88-
VITE_NUMBER_VARIABLE: Schema.number(),
89-
VITE_ENUM_VARIABLE: Schema.enum(['foo', 'bar'] as const),
90-
91-
// Optional variable
92-
VITE_OPTIONAL_VARIABLE: Schema.boolean.optional(),
93-
94-
// Specify string format
95-
VITE_AUTH_API_URL: Schema.string({ format: 'url', protocol: true }),
96-
97-
// Specify error message
98-
VITE_APP_PORT: Schema.number({ message: 'You must set a port !' }),
99-
100-
// Custom validator
101-
VITE_CUSTOM_VARIABLE: (key, value) => {
102-
if (!value) {
103-
throw new Error(`Missing ${key} env variable`)
104-
}
105-
106-
if (value.endsWith('foo')) {
107-
throw new Error('Value cannot end with "foo"')
108-
}
109-
110-
return value
111-
},
112-
}),
113-
],
89+
// Custom validator
90+
VITE_CUSTOM: (key, value) => {
91+
if (!value) throw new Error(`Missing ${key}`)
92+
if (value.endsWith('foo')) throw new Error('Cannot end with "foo"')
93+
return value
94+
},
11495
})
11596
```
11697

117-
## Standard Schema
98+
## Using Standard Schema
11899

119-
[standard-schema](https://github.com/standard-schema/standard-schema) is basically an attempt to standardize the way we can use validation libraries. It means that you can use any library that is compatible with it. Zod, Valibot, ArkType are popular libraries that are compatible with it.
100+
`standard-schema` provides a common interface for multiple validation libraries.
120101

121-
Here is an example of how to use it with the plugin:
102+
Here’s how to use it with Zod, Valibot, or ArkType, or any other library that supports it.
122103

123104
```ts
124105
import { defineConfig } from '@julr/vite-plugin-validate-env'
@@ -127,31 +108,29 @@ import * as v from 'valibot'
127108
import { type } from 'arktype'
128109

129110
export default defineConfig({
130-
validator: 'standard', // Make sure to use 'standard' validator
111+
validator: 'standard',
131112
schema: {
132-
// Zod
133-
VITE_ZOD_VARIABLE: z.string(),
134-
135-
// Valibot
136-
VITE_VALIBOT_VARIABLE: v.string(),
137-
138-
// Arktype
139-
VITE_ARKTYPE_VARIABLE: type.string(),
113+
VITE_ZOD_VAR: z.string(),
114+
VITE_VALIBOT_VAR: v.string(),
115+
VITE_ARKTYPE_VAR: type.string(),
140116
},
141117
})
142118
```
143119

144-
## Dedicated config file
120+
## Using a Dedicated `env.ts` Config File
145121

146-
You can also add a `env.ts` file at the root of your project to define your environment variables.
122+
You can move your env definitions to a separate file like this:
147123

148124
```ts
149125
// vite.config.ts
150126
import { defineConfig } from 'vite'
151-
import { ValidateEnv } from "@julr/vite-plugin-validate-env";
127+
import { ValidateEnv } from '@julr/vite-plugin-validate-env'
152128

153129
export default defineConfig({
154-
plugins: [ValidateEnv()],
130+
plugins: [ValidateEnv({
131+
// Optional: you can specify a custom path for the config file
132+
configFile: 'config/env'
133+
})],
155134
})
156135
```
157136

@@ -160,68 +139,12 @@ export default defineConfig({
160139
import { defineConfig, Schema } from '@julr/vite-plugin-validate-env'
161140

162141
export default defineConfig({
163-
VITE_MY_VAR: Schema.enum(['foo', 'bar'] as const),
164-
})
165-
```
166-
167-
### Custom config file path
168-
169-
By default, the plugin is looking for a file named `env.ts` at the root of your project. If you want to use a different file, you can specify the path to your file in the plugin options.
170-
171-
```ts
172-
// vite.config.ts
173-
import { defineConfig } from 'vite'
174-
import { ValidateEnv } from "@julr/vite-plugin-validate-env";
175-
176-
export default defineConfig({
177-
plugins: [ValidateEnv({ configFile: 'config/env' })],
178-
})
179-
```
180-
181-
This will look for a file named `env.ts` in the `config` folder at the root of your project. Make sure to not include the file extension in the path as the plugin will automatically search for `.js`, `.ts` and other valid file extensions.
182-
183-
## Transforming variables
184-
In addition to the validation of your variables, there is also a parsing that is done. This means that you can modify the value of an environment variable before it is injected.
185-
186-
Let's imagine the following case: you want to expose a variable `VITE_AUTH_API_URL` in order to use it to call an API. However, you absolutely need a trailing slash at the end of this environment variable. Here's how it can be done :
187-
188-
```ts
189-
// Built-in validation
190-
import { defineConfig, Schema } from '@julr/vite-plugin-validate-env'
191-
192-
export default defineConfig({
193-
VITE_AUTH_API_URL: (key, value) => {
194-
if (!value) {
195-
throw new Error(`Missing ${key} env variable`)
196-
}
197-
198-
if (!value.endsWith('/')) {
199-
return `${value}/`
200-
}
201-
202-
return value
203-
},
204-
})
205-
```
206-
207-
```ts
208-
// Zod validation
209-
import { defineConfig } from '@julr/vite-plugin-validate-env'
210-
import { z } from 'zod'
211-
212-
export default defineConfig({
213-
validator: 'standard',
214-
schema: {
215-
VITE_AUTH_API_URL: z
216-
.string()
217-
.transform((value) => value.endsWith('/') ? value : `${value}/`),
218-
},
142+
VITE_MY_VAR: Schema.enum(['foo', 'bar'] as const),
219143
})
220144
```
221145

222-
Now, in your client front-end code, when you call `import.meta.env.VITE_AUTH_API_URL`, you can be sure that it will always end with a slash.
223-
224146
## Typing `import.meta.env`
147+
225148
In order to have a type-safe `import.meta.env`, the ideal is to use the dedicated configuration file `env.ts`.
226149
Once this is done, you would only need to add an `env.d.ts` in `src/` folder to augment `ImportMetaEnv` (as [suggested here](https://vitejs.dev/guide/env-and-mode.html#env-files) ) with the following content:
227150

@@ -253,12 +176,40 @@ export const env: ImportMetaEnvAugmented = import.meta.env;
253176

254177
By using `env` instead of `import.meta.env` in your code, TypeScript will now throw an error if you try to access an unknown variable.
255178

256-
## Sponsors
257179

258-
If you like this project, [please consider supporting it by sponsoring it](https://github.com/sponsors/Julien-R44/). It will help a lot to maintain and improve it. Thanks a lot !
180+
## Transforming Variables
181+
182+
You can also **transform** values during parsing :
183+
184+
### Built-in:
185+
186+
```ts
187+
VITE_API_URL: (key, value) => {
188+
if (!value) throw new Error(`Missing ${key}`)
189+
return value.endsWith('/') ? value : `${value}/`
190+
}
191+
```
192+
193+
### With Zod:
194+
195+
```ts
196+
VITE_API_URL: z.string().transform((v) =>
197+
v.endsWith('/') ? v : `${v}/`
198+
)
199+
```
200+
201+
See the documentation of your validator for more details.
202+
203+
## 💖 Sponsors
204+
205+
If you find this useful, consider [sponsoring me](https://github.com/sponsors/Julien-R44)! It helps support and maintain the project 🙏
206+
207+
<p align="center">
208+
<img src="https://github.com/julien-r44/static/blob/main/sponsorkit/sponsors.png?raw=true">
209+
</p>
259210

260-
![](https://github.com/julien-r44/static/blob/main/sponsorkit/sponsors.png?raw=true)
211+
---
261212

262213
## License
263214

264-
[MIT](./LICENSE.md) License © 2022 [Julien Ripouteau](https://github.com/Julien-R44)
215+
MIT © [Julien Ripouteau](https://github.com/Julien-R44)

0 commit comments

Comments
 (0)