Environment variables
Rslib supports injecting environment variables or expressions into code during the build. This is useful for distinguishing runtime environments, replacing constants, and similar scenarios.
This page explains how to use environment variables in Rslib.
Default environment variables
Depending on the output format specified by format, Rslib either preserves source environment variables in the build output or replaces them with specific values at build time. The behavior is as follows:
Environment variables preserved in the build output are typically replaced by a downstream build tool or resolved by the target runtime; variables replaced at build time use Rsbuild's default values.
process.env.NODE_ENV
By default, Rslib automatically sets the process.env.NODE_ENV environment variable:
- It is set to
'production'when running build or calling rslib.build(), including in watch mode. - It is set to
'development'when running mf-dev or calling rslib.startMFDevServer().
These defaults are set in the current Node.js process, but process.env.NODE_ENV is not replaced in every output format. As shown in the table above, it is preserved in ESM and CJS output and replaced at build time in the other formats.
To override the default handling in the build output, such as disabling replacement or specifying a custom replacement value, use tools.rspack to configure Rspack's optimization.nodeEnv:
.env files
The Rslib CLI loads .env files from the project root by default. You can adjust this behavior with the following CLI options:
--env-mode <mode>: Load the corresponding.env.[mode]file.--env-dir <dir>: Specify the directory containing the.envfiles.--no-env: Disable loading.envfiles.
After loading, all environment variables are added to the current Node.js process, so they can be accessed through process.env in rslib.config.*. By default, only variables prefixed with PUBLIC_ are used to replace matching environment variable expressions at build time.
For supported .env file types, loading order, and override rules, see Rsbuild - .env files. For Public variable handling rules, see Rsbuild - Public variables.
Using define
To replace a global identifier in your code with another value or expression at build time, use source.define. For example:
- Explicit definitions take precedence over Rslib's default handling and are replaced in every output format.
- Values passed to
source.defineare code fragments, so string values must be converted withJSON.stringify(). - Define only the properties you need instead of replacing the entire
process.envobject.
For environment variable type declarations, see Rsbuild - Type declarations.
