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

unplugin-environment

v1.3.0

Published

A plugin for loading enviroment variables safely with schema validation, simple with virtual module, type-safe with intellisense, and better DX πŸ”₯ πŸš€ πŸ‘·. Support with Next.js, Vite, Webpack, Rollup, Rspack, Farm, and more.

Downloads

68

Readme

Table of Contents

Features

  • πŸ” Secure: Load environment variables safely with schema validation to avoid errors and prevent exposing sensitive information.
  • ✍️ Type-Safe: Automatically inferred types based on your schema configuration.
  • ⚑ Developer-Friendly: Lightweight and simple API for managing environment variables with seamless TypeScript integration.

Installation

Install via your preferred package manager:

npm install unplugin-environment       # npm

yarn add unplugin-environment          # yarn

bun add unplugin-environment           # bun

pnpm add unplugin-environment          # pnpm

Basic Usage

Configuration

// next.config.mjs
import Environment from 'unplugin-environment/webpack'

const nextConfig = {
    webpack(config){
        config.plugins.push(Environment('PREFIX_APP'))
        return config
    },
}

export default nextConfig

// vite.config.ts
import Environment from 'unplugin-environment/vite'

export default defineConfig({
  plugins: [
    Environment('PREFIX_APP'),
  ],
})

// farm.config.ts
import Environment from 'unplugin-environment/farm'

export default defineconfig({
  plugins: [
    Environment('PREFIX_APP'),
  ],
})

// rspack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-environment/rspack')('PREFIX_APP')
  ]
}

// rollup.config.js
import Environment from 'unplugin-environment/rollup'

export default {
  plugins: [
    Environment('PREFIX_APP'),
  ],
}

// rolldown.config.js
import Environment from 'unplugin-environment/rolldown'

export default {
  plugins: [
    Environment('PREFIX_APP'),
  ],
}

// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-environment/webpack')("PREFIX_APP")
  ]
}

// esbuild.config.js
import { build } from 'esbuild'
import Environment from 'unplugin-environment/esbuild'

build({
  plugins: [Environment('PREFIX_APP')],
})

// astro.config.mjs
import { defineConfig } from 'astro/config'
import Environment from 'unplugin-environment/astro'

build({
  plugins: [Environment('PREFIX_APP')],
})

Schema Validation

Use the schema option with zod for validating environment variables. This automatically creates a virtual module with types.

Environment({
    match: 'PREFIX_', // or ['PREFIX_', 'PREFIX2_']
    schema: {
        PREFIX_APP_NAME: z.string().min(1).default('My App'),
        PREFIX_APP_PORT: z.coerce.number().min(1).default(3000),
    },
})

Intellisense with TypeScript

To enable Intellisense for environment variables, add the following to your tsconfig.json:

{
    "compilerOptions": {
        "types": ["unplugin-environment/client"]
    }
}

Accessing Environment Variables

You can access environment variables from the virtual module @env:

import { env } from '@env'

console.log(env.PREFIX_APP_NAME)

If you want to customize the module name, use the moduleEnvName option:

// in plugin configuration
Environment({
    match: 'PREFIX_', // or ['PREFIX_', 'PREFIX2_']
    schema: ...,
    moduleEnvName: 'MYENV',
})


// you can access it from `MYENV` module
import { env } from 'MYENV'

console.log(env.PREFIX_APP_NAME)

Client/Server Environment

To handle environment variables separately for client and server, use the client and server options. This allows for precise control over which variables are accessible in different environments.

[!NOTE] When using the client and server options, you cannot access environment variables through the @env module. Instead, use @env/client for client-side variables and @env/server for server-side variables by default.

Example configuration:

Environment({
    client: {
        match: 'CLIENT_',
        schema: {
            CLIENT_APP_NAME: z.string().min(1).default('My App'),
        },
    },
    server: {
        match: 'SERVER_',
        schema: {
            SERVER_APP_DB_URL: z.string().min(1).default('postgres://localhost:5432/mydb'),
        }
    },
})

If you'd like to change the default module names @env/client and @env/server, you can use the optional moduleEnvName key to define a custom module name for accessing the environment variables.

[!CAUTION] When customizing moduleEnvName for client and server, ensure the module names are different. Using the same name for both client and server can cause conflicts and unpredictable behavior.

Environment({
    client: {
        match: 'CLIENT_',
        schema: {
            CLIENT_APP_NAME: z.string().min(1).default('My App'),
        },
        moduleEnvName: '@myenv/client', // Optional: Customize the client module name
    },
    server: {
        match: 'SERVER_',
        schema: {
            SERVER_APP_DB_URL: z.string().min(1).default('postgres://localhost:5432/mydb'),
        },
        moduleEnvName: '@myenv/server', // Optional: Customize the server module name
    },
})

Accessing Client/Server Environment

// client environment
import { env } from '@env/client'

env.CLIENT_APP_NAME // typed with string

// server environment
import { env } from '@env/server'

env.SERVER_APP_DB_URL // typed with string

Acknowledgements