In my dev environment I cannot pull environment variables
.env is at the top level
I have a .env variable VITE_DB_PASSWORD=12345
I am pulling it into a different file to connect with my database
const pw: string = import.meta.env.VITE_DB_PASSWORD;
this is the console error
const pw: string = import.meta.env.VITE_DB_PASSWORD;
^
TypeError: Cannot read properties of undefined (reading 'VITE_DB_PASSWORD')
vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
// Ensure the output is in ES module format
target: "esnext",
rollupOptions: {
output: {
format: "esm",
},
},
},
});
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"types": ["node"] // Add this line to include Node.js types
},
"include": ["src", "node_modules/@types"]
}
First the typescript compiler was giving an error about commonjs files, which I fixed by adding
"module": "ESNext",
to tsconfig.json
I am not sure why the error is happening.
New contributor
Danny Byrne is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.