npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vite-env-caster-v2

v0.0.4

Published

New way to use environment variables in Vite

Downloads

5

Readme

Vite Env Caster

Casting your Environment Variables to real javascript's type.

✨ Features

⚡️ Fast: Everything is processed at build-time, zero run-time's code, your application has been no impacted.

🛠️ Simple: Starting use your environment variables with no configuration.

🔌 Customizable: Adding your custom caster or replacing default's caster.

Ts Typescript: Typescript supported.

Getting started

Installation

With yarn

yarn add @niku/vite-env-caster

With npm

npm i --save @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

It's very simple.

Example:

You have file .env like this:

// .env.development
VITE_API_URL=http://example.com
VITE_DEFAULT_PAGE_SIZE=10
VITE_AUTH_ENABLED=false
VITE_ARRAY_EXAMPLE=[123,abc,def,456]

Then, you can import and use it's variables by import as a module.

// 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_AUTH_ENABLED) // false
console.log(appEnv.VITE_ARRAY_EXAMPLE) // [123, "abc", "def", 456]

Force cast to type

If you need to cast environment variable to a static type, you can define that type in variable.

Example:

// .env.development
VITE_IS_A_NUMBER_IN_STRING=10|string
VITE_IS_A_BOOLEAN_IN_STRING=false|string
VITE_IS_ARRAY_OF_NUMBER=[123,abc,def,456]|array[number]
VITE_IS_ARRAY_OF_STRING=[123,abc,def,456]|array[string]

Then.

// src/main.ts
import appEnv from "app-env";

console.log(appEnv.VITE_IS_A_NUMBER_IN_STRING) // "10"
console.log(appEnv.VITE_IS_A_BOOLEAN_IN_STRING) // "false"
console.log(appEnv.VITE_IS_ARRAY_OF_NUMBER) // [123, NaN, NaN, 456]
console.log(appEnv.VITE_IS_ARRAY_OF_STRING) // ["123", "abc", "def", "456"]

Limitation

By default, this plugin only supports these 4 types: boolean, string, number, (number | string)[].

If you need to cast others type, try to add your custom caster.

Typescript support

By default, file env.d.ts will be generated at root of project. You can include it in your tsconfig.json.

// tsconfig.json
{
  "include": ["env.d.ts", ...]
}

Configuration

Transform key

In some case, you may want to use environment variable with other convention. Like use with camel case and remove prefix VITE_. You can customize it very easy.

// vite.config.ts
import EnvCaster from '@niku/vite-env-caster';
import {camelCase} from "lodash";

export default defineConfig({
  plugins: [
    EnvCaster({
      transformKey: (plainKey) => camelCase(plainKey.replace("VITE_", ""))
    }),
  ],
})

Then, you can use environment variable in camel case.

// src/main.ts
import appEnv from "app-env";

console.log(appEnv.apiUrl) // "http://example.com"
console.log(appEnv.defaultPageSize) // 10
console.log(appEnv.authEnabled) // false
console.log(appEnv.arrayExample) // [123, "abc", "def", 456]

Custom Type Caster

This is an example for number caster.

// vite.config.ts
import EnvCaster from '@niku/vite-env-caster';
import {camelCase} from "lodash";

export default defineConfig({
  plugins: [
    EnvCaster({
      typeCasters: {
        number: {
          // Check if variable is number
          isType(plainValue, type) {
            if (type) { // Forced type
              return type.toLowerCase() === "number";
            }

            // Auto detect
            return !Number.isNaN(Number(plainValue));
          },
          // Cast variable to number
          castValue(plainValue) {
            return Number(plainValue);
          },
          // Type in declaration file
          typescriptType() {
            return "number";
          },
        }
      },
    }),
  ],
})

All options

| Option | Description | Default | | ------------ | ------------------------------------------------------------------------ | ---------- | | moduleName | Virtual module name you will import env from. | "app-env" | | exportName | Export module name will be generated in declaration file. | "appEnv" | | declaration | Should plugin generate declaration file. Can be passed a string as path. | "env.d.ts" | | typeCasters | List custom type casters. | No | | transformKey | A function to transform environment variable's key. | No |