Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I validate in build-time using Vite? #17

Open
yamcodes opened this issue Aug 22, 2024 · 0 comments
Open

How do I validate in build-time using Vite? #17

yamcodes opened this issue Aug 22, 2024 · 0 comments

Comments

@yamcodes
Copy link

yamcodes commented Aug 22, 2024

Hey, thanks for the great library.
I've set this up in my ./config.ts file as so:

import { parseEnv, z } from "znv";
import type { Environment } from "types";

const envSchema = z.object({
    VITE_MY_URL: z.string().url(),
});

/**
 * Validated environment variables
 */
export const env = parseEnv(import.meta.env, envSchema.shape);

/**
 * This const comes from the extension in `.env.%MODE%` files
 */
export const environment = import.meta.env.MODE as Environment;

An error is thrown when VITE_MY_URL is not supplied during runtime (i.e., in the browser).
However, is there a way to throw an error when running vite build? Currently it passes although I'd expect it to fail.

I thought the solution to run tsx ./config.ts && vite build, but that is not working and throwing this error:

> [email protected] validate /Users/yamcodes/code/my-repo
> tsx src/config.ts

file:///Users/yamcodes/code/my-repo/node_modules/.pnpm/[email protected][email protected]/node_modules/znv/dist/parse-env.js:32
        const envValue = env[key];
                            ^

TypeError: Cannot read properties of undefined (reading 'VITE_MY_URL')
    at parseEnv (/Users/yamcodes/code/my-repo/node_modules/.pnpm/[email protected][email protected]/node_modules/znv/src/parse-env.ts:116:25)
    at <anonymous> (/Users/yborodetsky/code/storemavens/mvns-core/services/mvns-home/src/config.ts:15:20)
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

Node.js v20.11.1
 ELIFECYCLE  Command failed with exit code 1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant