znv icon indicating copy to clipboard operation
znv copied to clipboard

How do I validate in build-time using Vite?

Open yamcodes opened this issue 6 months ago • 0 comments

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.

yamcodes avatar Aug 22 '24 12:08 yamcodes