CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rsbuild--core

The Rspack-based build tool providing high-performance bundling with comprehensive development features and plugin system.

Pending
Overview
Eval results
Files

environment-variables.mddocs/

Environment Variables

Environment variable loading and management from .env files with mode-specific support. Provides secure and flexible configuration management for different deployment environments.

Capabilities

Load Environment Variables

Load environment variables from .env files with mode-specific support.

/**
 * Load environment variables from .env files
 * @param options - Environment loading options
 * @returns Environment loading result with parsed variables
 */
function loadEnv(options?: LoadEnvOptions): LoadEnvResult;

interface LoadEnvOptions {
  /** Working directory to search for .env files */
  cwd?: string;
  /** Environment mode for file selection */
  mode?: string;
  /** Variable prefixes to expose to client */
  prefixes?: string[];
  /** Process environment variables to merge */
  processEnv?: Record<string, string>;
}

interface LoadEnvResult {
  /** Raw parsed variables from .env files */
  parsed: Record<string, string>;
  /** Paths of loaded .env files */
  filePaths: string[];
  /** Raw public variables before formatting */
  rawPublicVars: Record<string, string | undefined>;
  /** Formatted public variables for client use */
  publicVars: Record<string, string>;
  /** Cleanup function to restore original environment */
  cleanup: () => void;
}

Usage Examples:

import { loadEnv } from "@rsbuild/core";

// Load from default location
const { parsed, publicVars, filePaths } = loadEnv();
console.log("Parsed variables:", parsed);
console.log("Client variables:", publicVars);

// Load with specific mode and prefixes
const prodEnv = loadEnv({ 
  mode: "production",
  prefixes: ["RSBUILD_", "PUBLIC_"],
});
console.log("Production public vars:", prodEnv.publicVars);

// Load from custom directory with cleanup
const { parsed, cleanup } = loadEnv({ 
  cwd: "/path/to/project",
  mode: "staging",
});
console.log("Staging variables:", parsed);
// Restore environment when done
cleanup();

Environment File Resolution

Rsbuild loads environment files in the following order (higher priority first):

  1. .env.{mode}.local (e.g., .env.production.local)
  2. .env.local (always loaded except in test mode)
  3. .env.{mode} (e.g., .env.production)
  4. .env

File Examples:

# .env (base environment variables)
DATABASE_URL=localhost:5432
API_VERSION=v1

# .env.local (local overrides, ignored by git)
DATABASE_URL=localhost:3306
DEBUG=true

# .env.production (production-specific)
DATABASE_URL=prod-db.example.com:5432
API_URL=https://api.example.com

# .env.production.local (production local overrides)
DEBUG=false
LOG_LEVEL=error

Environment Variable Processing

interface LoadEnvResult {
  /** 
   * Merged environment variables from all loaded files
   * Variables from higher priority files override lower priority ones
   */
  env: Record<string, string>;
  
  /** 
   * Parsed variables organized by source file
   * Useful for debugging which file provided which variables
   */
  parsed: Record<string, Record<string, string>>;
}

Processing Rules:

  • Variables are loaded and merged with higher priority files overriding lower priority
  • Empty values are treated as empty strings, not undefined
  • Comments (lines starting with #) are ignored
  • Multi-line values are supported using quotes
  • Variable expansion is supported using ${VARIABLE} syntax

Client-Side Environment Variables

Environment variables available in client-side code during build:

// Available in client code
declare const import.meta.env: {
  /** Build mode */
  MODE: 'development' | 'production' | 'none';
  /** True if MODE is 'development' */
  DEV: boolean;
  /** True if MODE is 'production' */  
  PROD: boolean;
  /** Base URL from server.base config */
  BASE_URL: string;
  /** Asset prefix URL */
  ASSET_PREFIX: string;
  
  // Custom variables (must be prefixed)
  [key: string]: any;
};

Variable Prefixing:

Only environment variables with specific prefixes are exposed to client code:

  • RSBUILD_ - Rsbuild-specific variables
  • PUBLIC_ - Public variables exposed to client
  • Built-in variables (MODE, DEV, PROD, etc.)
# .env
RSBUILD_API_URL=https://api.example.com  # Available in client
PUBLIC_VERSION=1.0.0                     # Available in client
PRIVATE_KEY=secret123                    # Server-only, not exposed

Integration with Configuration

Environment variables can be used in Rsbuild configuration:

import { defineConfig, loadEnv } from "@rsbuild/core";

const { env } = loadEnv();

export default defineConfig({
  source: {
    define: {
      // Expose variables to client code
      'process.env.API_URL': JSON.stringify(env.RSBUILD_API_URL),
      'process.env.VERSION': JSON.stringify(env.PUBLIC_VERSION),
    },
  },
  
  server: {
    port: parseInt(env.PORT || "3000"),
    proxy: env.PROXY_URL ? {
      "/api": env.PROXY_URL,
    } : undefined,
  },
  
  output: {
    assetPrefix: env.ASSET_PREFIX || "/",
  },
});

Mode-Specific Loading

// Load development-specific environment
const devEnv = loadEnv({ mode: "development" });

// Load production-specific environment  
const prodEnv = loadEnv({ mode: "production" });

// Load staging-specific environment
const stagingEnv = loadEnv({ mode: "staging" });

Environment Variable Expansion

Support for variable expansion within .env files:

# .env
BASE_URL=https://example.com
API_URL=${BASE_URL}/api
FULL_API_URL=${API_URL}/v1

# Results in:
# BASE_URL=https://example.com
# API_URL=https://example.com/api  
# FULL_API_URL=https://example.com/api/v1

TypeScript Support

Type-safe environment variable access:

// env.d.ts
interface ImportMetaEnv {
  readonly RSBUILD_API_URL: string;
  readonly PUBLIC_VERSION: string;
  readonly MODE: 'development' | 'production' | 'none';
  readonly DEV: boolean;
  readonly PROD: boolean;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

// Usage in code
const apiUrl = import.meta.env.RSBUILD_API_URL; // Type-safe
const isDev = import.meta.env.DEV; // boolean

Security Considerations

Server-Side Only Variables:

Variables without proper prefixes are only available on the server side:

// In server-side code (Node.js)
const dbPassword = process.env.DATABASE_PASSWORD; // Available

// In client-side code (browser)
const dbPassword = process.env.DATABASE_PASSWORD; // undefined
const apiUrl = import.meta.env.RSBUILD_API_URL; // Available

Best Practices:

  • Use .env.local for local development secrets
  • Add .env.local to .gitignore
  • Use proper prefixes for client-exposed variables
  • Validate required environment variables at startup
  • Use separate .env files for different environments

Integration with CreateRsbuild

interface CreateRsbuildOptions {
  /** Environment variable loading configuration */
  loadEnv?: boolean | LoadEnvOptions;
}

Usage:

// Auto-load environment variables
const rsbuild = await createRsbuild({
  loadEnv: true, // Uses default options
});

// Custom environment loading
const rsbuild = await createRsbuild({
  loadEnv: {
    mode: "production",
    cwd: "./config",
  },
});

// Disable automatic environment loading
const rsbuild = await createRsbuild({
  loadEnv: false,
});

Install with Tessl CLI

npx tessl i tessl/npm-rsbuild--core

docs

cli-integration.md

configuration-management.md

core-build-system.md

development-server.md

environment-system.md

environment-variables.md

index.md

plugin-system.md

tile.json