Skip to content

Commit b49bf8c

Browse files
committed
feat: support envDir option
Close #6
1 parent eec9e04 commit b49bf8c

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

src/index.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { cwd } from 'process'
2-
import { type Plugin, loadEnv } from 'vite'
2+
import path from 'node:path'
3+
import { type Plugin, loadEnv, normalizePath } from 'vite'
34
import { createConfigLoader as createLoader } from 'unconfig'
45
import { builtinValidation } from './validators/builtin'
56
import { zodValidation } from './validators/zod'
@@ -47,7 +48,16 @@ function getNormalizedOptions(options: PluginOptions) {
4748
*/
4849
async function validateEnv(userConfig: UserConfig, envConfig: ConfigEnv, options?: PluginOptions) {
4950
const rootDir = userConfig.root || cwd()
50-
const env = loadEnv(envConfig.mode, rootDir, userConfig.envPrefix)
51+
52+
const resolvedRoot = normalizePath(
53+
userConfig.root ? path.resolve(userConfig.root) : process.cwd()
54+
)
55+
56+
const envDir = userConfig.envDir
57+
? normalizePath(path.resolve(resolvedRoot, userConfig.envDir))
58+
: resolvedRoot
59+
60+
const env = loadEnv(envConfig.mode, envDir, userConfig.envPrefix)
5161

5262
const isInlineConfig = options !== undefined
5363
if (!isInlineConfig) {

tests/common.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,19 @@ test.group('vite-plugin-validate-env', (group) => {
136136
}
137137
})
138138

139+
test('Should use envDir option from vite config', async ({ assert }) => {
140+
assert.plan(1)
141+
142+
const plugin = ValidateEnv({ VITE_XXX: Schema.string() })
143+
144+
await fs.add(`./env-directory/.env.development`, `VITE_XXX=bonjour`)
145+
146+
// @ts-ignore
147+
await plugin.config({ ...viteConfig, envDir: './env-directory' }, viteEnvConfig)
148+
149+
assert.equal(process.env.VITE_XXX, 'bonjour')
150+
})
151+
139152
test('Display multiple errors', async ({ assert }) => {
140153
assert.plan(2)
141154

0 commit comments

Comments
 (0)