Ahora estoy usando un marco (vite) que inyecta variables de entorno en import.meta.env .
Anteriormente pude crear un archivo env.d.ts para proporcionar tipos a process.env
declare global { namespace NodeJS { interface ProcessEnv { GITHUB_AUTH_TOKEN: string; NODE_ENV: 'development' | 'production'; PORT?: string; PWD: string; } } }He intentado lo siguiente pero no funciona.
declare global { namespace NodeJS { interface ImportMeta { GITHUB_AUTH_TOKEN: string; NODE_ENV: 'development' | 'production'; PORT?: string; PWD: string; } } }Tuve problemas similares y lo resolvió por
tsconfig.json
{ ... "compilerOptions": { ... "target": "ESNext", "types": ["vite/client"] } } Tener vite instalado como una dependencia de desarrollo.
De acuerdo con la documentación aquí https://vitejs.dev/guide/env-and-mode.html#intellisense , puede hacer lo siguiente:
// env.d.ts interface ImportMetaEnv extends Readonly<Record<string, string>> { readonly VITE_APP_TITLE: string // more env variables... } interface ImportMeta { readonly env: ImportMetaEnv }Si usa SvelteKit v1.0.0-next.120 y Vite 2.4.0, env debe ser una propiedad de ImportMeta en global.d.ts. Aquí hay un ejemplo:
interface ImportMeta { env: { VITE_DATABASE_URL?: string VITE_WEB_URL?: string VITE_BRAINTREE_GATEWAY?: string VITE_BRAINTREE_DESCRIPTOR?: string VITE_RECAPTCHA_SECRET_KEY?: string VITE_EMAIL_FROM?: string VITE_EMAIL_ADMINS?: string VITE_SEND_IN_BLUE_KEY?: string VITE_SEND_IN_BLUE_URL?: string VITE_RECAPTCHA_SITE_KEY?: string } }Está documentado aquí: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#support-for-importmeta
Así que ya casi estás allí:
interface ImportMeta { env: { GITHUB_AUTH_TOKEN: string; NODE_ENV: 'development' | 'production'; PORT?: string; PWD: string; }; } Pero tenga en cuenta que in vite todas las variables de entorno deben tener el prefijo VITE_ para que ninguna de esas variables de entorno esté disponible en la aplicación.
Lo hice funcionar usando lo siguiente:
interface ImportMetaEnv { VITE_PORT?: string; VITE_AUTH_TOKEN?: string; }