Skip to content

Commit fafb3b2

Browse files
committed
refactor: some minor refactor
1 parent 25cdfae commit fafb3b2

File tree

3 files changed

+50
-25
lines changed

3 files changed

+50
-25
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ interface ImportMetaEnv extends ImportMetaEnvAugmented {
177177

178178
In some cases, you might want to validate environment variables outside of Vite and reuse the same schema. You can do so by using the `loadAndValidateEnv` function directly. This function will validate and also load the environment variables inside the `process.env` object.
179179

180-
> ![WARNING]
180+
> [!WARNING]
181181
> `process.env` only accept string values, so don't be surprised if a `number` or `boolean` variable comes back as a string when accessing it after validation.
182182
183183
```ts

src/index.ts

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -124,35 +124,30 @@ export const ValidateEnv = (options?: PluginOptions): Plugin => {
124124
// @ts-expect-error - only used for testing as we need to keep each instance of the plugin unique to a test
125125
ui: process.env.NODE_ENV === 'testing' ? ui : undefined,
126126
name: 'vite-plugin-validate-env',
127-
config: ({ envDir, envPrefix, root }, { mode }) =>
128-
validateEnv(ui, { envDir, envPrefix, root, mode }, options).then((variables) => ({
129-
define: variables.reduce(
130-
(acc, { key, value }) => {
131-
acc[`import.meta.env.${key}`] = JSON.stringify(value)
132-
return acc
133-
},
134-
{} as Record<string, string>,
135-
),
136-
})),
127+
config: async ({ envDir, envPrefix, root }, { mode }) => {
128+
const env = await validateEnv(ui, { envDir, envPrefix, root, mode }, options)
129+
const define = Object.fromEntries(
130+
env.map(({ key, value }) => [`import.meta.env.${key}`, JSON.stringify(value)]),
131+
)
132+
133+
return { define }
134+
},
137135
}
138136
}
139137

140138
/**
141-
* Load environment variables using the provided Vite configuration
142-
* and validate them against a schema the same way `ValidateEnv` does it
143-
* @returns An object mapping environment variable names to validation results
139+
* Validate environment variables and load them inside `process.env`
140+
* Can be useful when you want to validate outside of Vite's build process.
144141
*/
145-
export const loadAndValidateEnv = (config: ConfigOptions, options?: PluginOptions) => {
142+
export const loadAndValidateEnv = async (config: ConfigOptions, options?: PluginOptions) => {
146143
const ui = initUi()
147-
return validateEnv(ui, config, options).then((variables) =>
148-
variables.reduce(
149-
(acc, { key, value }) => {
150-
acc[key] = value
151-
return acc
152-
},
153-
{} as Record<string, any>,
154-
),
155-
)
144+
const variables = await validateEnv(ui, config, options)
145+
146+
for (const { key, value } of variables) {
147+
process.env[key] = value
148+
}
149+
150+
return Object.fromEntries(variables.map(({ key, value }) => [key, value]))
156151
}
157152

158153
export const defineConfig = <T extends PluginOptions>(config: T): T => config

tests/common.spec.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { test } from '@japa/runner'
22

3-
import { Schema } from '../src/index.js'
3+
import { loadAndValidateEnv, Schema } from '../src/index.js'
44
import { createEnvFile, executeValidateEnv, ValidateEnv } from './helpers.js'
55

66
test.group('vite-plugin-validate-env', () => {
@@ -183,3 +183,33 @@ test.group('vite-plugin-validate-env', () => {
183183
assert.isDefined(messages.find((message) => message.includes('cyan(VITE_TESTX): not boolean')))
184184
})
185185
})
186+
187+
test.group('vite-plugin-validate-env - node usage', () => {
188+
test('Basic validation', async ({ assert, fs }) => {
189+
await createEnvFile({ VITE_TEST: 'not boolean' })
190+
const validate = async () =>
191+
await loadAndValidateEnv(
192+
{ mode: 'development', root: fs.basePath },
193+
{ VITE_TEST: Schema.boolean() },
194+
)
195+
196+
await assert.rejects(async () => {
197+
await validate()
198+
}, /"VITE_TEST" env variable must be a boolean \(Current value: "not boolean"\)/)
199+
200+
delete process.env.VITE_TEST
201+
})
202+
203+
test('assign to process.env', async ({ assert, fs }) => {
204+
await createEnvFile({ VITE_TEST: 'true' })
205+
const result = await loadAndValidateEnv(
206+
{ mode: 'development', root: fs.basePath },
207+
{ VITE_TEST: Schema.boolean() },
208+
)
209+
210+
assert.deepEqual(result, { VITE_TEST: true })
211+
assert.equal(process.env.VITE_TEST, 'true')
212+
213+
delete process.env.VITE_TEST
214+
})
215+
})

0 commit comments

Comments
 (0)