Skip to content

[Feature]: Add dryRun option to parse env files without modifying process.env #4638

@curlykay

Description

@curlykay

What problem does this feature solve?

Description
Currently, loadEnv() merges environment variables from .env,.env[.local] .env[.mode], and .env[.mode[.local]] files into process.env. While useful for build processes, this causes environment pollution when using custom CLI tools outside rsbuild's build/dev flows.

The current loadEnv() + cleanup() pattern has limitations when environment variables already exist before loading:

  1. cleanup simply deletes injected variables rather than restoring original values
  2. Pre-existing values get permanently erased when using this pattern

Proposal
Add a dryRun boolean option to loadEnv(). When enabled:

  1. Files are still loaded/merged using existing priority rules
  2. Parsed values are returned in the parsed field
  3. No modifications are made to process.env

(Note: loadEnv() May need a separate processEnv configuration for advanced environment injection control,like:https://dotenvx.com/docs/advanced/parse-process-env)

What does the proposed API look like?

Use Case
Creating custom CLI tools that need env values without side effects:

# .env
HELLO=WORLD
import { loadEnv } from '@rsbuild/core';

// In custom CLI script
const { parsed } = loadEnv({
  dryRun: true, // Prevent env injection
  mode: 'production'
});

console.log(parsed.HELLO); //   WORLD   Value from .env files
console.log(process.env.HELLO); // undefined (no pollution)

Behavior Comparison

Option Returns parsed Modifies process.env
dryRun:true
Default

Implementation Notes

  1. Should maintain full compatibility with existing API
  2. Should preserve existing environment variable merging logic
  3. Documentation update needed for new option

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions