DEV Community

Mạnh Phạm
Mạnh Phạm

Posted on

Vite environment variable's type casting/transforming

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 ImportMetaEnvanytime 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
Enter fullscreen mode Exit fullscreen mode

yarn

yarn add @niku/vite-env-caster
Enter fullscreen mode Exit fullscreen mode

Then add EnvCaster to you Vite's plugins.

// vite.config.ts
import EnvCaster from '@niku/vite-env-caster';

export default defineConfig({
  plugins: [
    EnvCaster({ /* options */ }),
  ],
});
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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"]
}
Enter fullscreen mode Exit fullscreen mode

Then, you will get auto complete like this.

Vite env caster

Conclusion

Thanks for reading, I hope that this post is useful to you.

Top comments (0)