Closed juanzitelli closed 1 year ago
In order to trigger the validation during build time, you can import the env.ts
in vite.config.ts
like import "./env";
.
In order to trigger the validation during build time, you can import the
env.ts
invite.config.ts
likeimport "./env";
.
I know, the thing is that whenever I try to run the build or dev command, the package cannot read import.meta.env saying it's undefined, therefore it's not loading .env file
Hmm, wasn't realize that Vite doesn't load env in configuration file.
However, there's a workaround for that, it feels hacky but it get the job done. You can manually load the env in vote.config.ts
via Vite loadEnv
function.
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig(async ({ mode }) => {
import.meta.env = loadEnv(mode, process.cwd());
await import("./src/env");
return {
plugins: [react()],
};
});
Hmm, wasn't realize that Vite doesn't load env in configuration file.
However, there's a workaround for that, it feels hacky but it get the job done. You can manually load the env in
vote.config.ts
via ViteloadEnv
function.import { defineConfig, loadEnv } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig(async ({ mode }) => { import.meta.env = loadEnv(mode, process.cwd()); await import("./src/env"); return { plugins: [react()], }; });
I realized that I missed the import of the "./env.ts" file on the example. Sorry about that! I will try your solution and let you know if it worked or not. Thanks in advance!
I've tried @chungweileong94's workaround and it solved the issue! Now import.meta.env is loaded correctly so it can be then parsed using zod. Thanks!
"import.meta" is not available with the "cjs" output format and will be empty
I am getting the above error while trying to do the following.
import.meta.env = loadEnv(mode, process.cwd());
I have my env file in src/env/env.ts and I am using vue with vite.
Problem
I can't get build-time validation working on a vitejs app. I want to run the schema validation on build time so I can check if all required environment variables are defined or not.
Repro
npm create vite@latest
npm install @t3-oss/env-core zod
VITE_TEST_VAR="ABC" VITE_MISSING="123"
@t3-oss/env-core
requiredenv.ts
file with the following contentApp.tsx
(so we verify that env vars are actually usable within the client app)