The Rspack-based build tool providing high-performance bundling with comprehensive development features and plugin system.
—
Environment variable loading and management from .env files with mode-specific support. Provides secure and flexible configuration management for different deployment environments.
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();Rsbuild loads environment files in the following order (higher priority first):
.env.{mode}.local (e.g., .env.production.local).env.local (always loaded except in test mode).env.{mode} (e.g., .env.production).envFile 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=errorinterface 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:
#) are ignored${VARIABLE} syntaxEnvironment 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 variablesPUBLIC_ - Public variables exposed to client# .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 exposedEnvironment 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 || "/",
},
});// 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" });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/v1Type-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; // booleanServer-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; // AvailableBest Practices:
.env.local for local development secrets.env.local to .gitignoreinterface 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