You can try using this package:
https://www.npmjs.com/package/@niku/vite-env-caster
This package generate types from your env file and cast environment variables to real type.
Firstly, install it with your package manager:
# npm
npm install @niku/vite-env-caster
# yarn
yarn add @niku/vite-env-caster
#pnpm
pnpm add @niku/vite-env-caster
Add plugin exported from package above to your vite config's plugins:
// vite.config.ts
import EnvCaster from '@niku/vite-env-caster';
export default defineConfig({
plugins: [
EnvCaster({ /* options */ }),
],
})
By default, file env.d.ts will be generated at root of project. You can include it in your tsconfig.json.
{
"include": ["env.d.ts", ...]
}
Then, instead of import env from import.meta.env, you have to import them from app-env
import appEnv from "app-env";
export const EnvironmentProvider: React.FC<EnvironmentProps> = ({ children }) => (
<EnvironmentContext.Provider value={{
APP_NAME: appEnv.VITE_APP_NAME,
GQL_URI: appEnv.VITE_GQL_URI
}}>
{ children }
</EnvironmentContext.Provider>
)