Introduction
When developing a frontend app, we usually use environment variables(env) to store app's config, secret key,...And Vite, a popular development tool, also support env file, with Typescript supportted. But, all things we get from it is string
and we need to update ImportMetaEnv
anytime we add new variable.
So, package vite-env-caster
is published to solve these issues.
Installation
Install package using yarn
or npm
:
npm
npm i @niku/vite-env-caster --save
yarn
yarn add @niku/vite-env-caster
Then add EnvCaster
to you Vite's plugins.
// vite.config.ts
import EnvCaster from '@niku/vite-env-caster';
export default defineConfig({
plugins: [
EnvCaster({ /* options */ }),
],
});
Usage
Environment variable's type casting
Instead of string
, you can use your env
with it own type.
Example:
You have a file .env
like this:
VITE_API_URL=http://example.com
VITE_DEFAULT_PAGE_SIZE=10
VITE_FACEBOOK_AUTH_ENABLED=false
VITE_ARRAY_EXAMPLE=[123,abc,def,456,false]
Then, you can import and use it's variables by import as a module (default app-env
).
// src/main.ts
import appEnv from "app-env";
console.log(appEnv.VITE_API_URL) // "http://example.com"
console.log(appEnv.VITE_DEFAULT_PAGE_SIZE) // 10
console.log(appEnv.VITE_FACEBOOK_AUTH_ENABLED) // false
console.log(appEnv.VITE_ARRAY_EXAMPLE) // [123, "abc", "def", 456, false]
Typescript support
To using env
with Typescript, You just need to include it in your tsconfig.json
. By default, file env.d.ts
will be generated at root of project.
{
"include": ["env.d.ts"]
}
Then, you will get auto complete like this.
Conclusion
Thanks for reading, I hope that this post is useful to you.
Top comments (0)