乐闻世界logo
搜索文章和话题

How does Rspack manage environment variables?

2月21日 15:34

Rspack's environment variable management is an important feature in frontend development, helping developers use different configurations in different environments. Here's a detailed explanation of Rspack's environment variable management:

Basic Concepts of Environment Variables

Environment variables are variables injected into code at build time, used to distinguish configurations for different environments (development, testing, production).

Environment Variable Definition Methods

1. DefinePlugin

Use DefinePlugin to define environment variables:

javascript
const { DefinePlugin } = require('@rspack/core'); module.exports = { plugins: [ new DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), 'process.env.API_URL': JSON.stringify('https://api.example.com'), 'process.env.VERSION': JSON.stringify('1.0.0') }) ] }

2. .env Files

Use .env files to manage environment variables:

bash
# .env.development NODE_ENV=development API_URL=http://localhost:3000 DEBUG=true # .env.production NODE_ENV=production API_URL=https://api.example.com DEBUG=false

3. Command Line Arguments

Pass environment variables via command line:

bash
# Unix/Linux NODE_ENV=production API_URL=https://api.example.com npx rspack build # Windows set NODE_ENV=production&& set API_URL=https://api.example.com&& npx rspack build # Use cross-env (cross-platform) npx cross-env NODE_ENV=production API_URL=https://api.example.com npx rspack build

Environment Variable Loading

1. dotenv-webpack-plugin

Use dotenv-webpack-plugin to load .env files:

javascript
const Dotenv = require('dotenv-webpack'); module.exports = { plugins: [ new Dotenv({ path: './.env.production', safe: true, systemvars: true, silent: true }) ] }

2. Custom Environment Variable Loading

javascript
const fs = require('fs'); const path = require('path'); function loadEnv(mode) { const envPath = path.resolve(__dirname, `.env.${mode}`); const envContent = fs.readFileSync(envPath, 'utf8'); const envVars = {}; envContent.split('\n').forEach(line => { const [key, value] = line.split('='); if (key && value) { envVars[key.trim()] = value.trim(); } }); return envVars; } const envVars = loadEnv(process.env.NODE_ENV || 'development'); module.exports = { plugins: [ new DefinePlugin({ 'process.env': JSON.stringify(envVars) }) ] }

Environment Variable Usage

1. Using in Code

javascript
// Use environment variables const apiUrl = process.env.API_URL; const isDevelopment = process.env.NODE_ENV === 'development'; const version = process.env.VERSION; console.log('API URL:', apiUrl); console.log('Is Development:', isDevelopment);

2. TypeScript Type Definitions

typescript
// env.d.ts declare namespace NodeJS { interface ProcessEnv { NODE_ENV: 'development' | 'production' | 'test'; API_URL: string; VERSION: string; DEBUG: string; } }

Environment Configuration

1. Multi-environment Configuration

javascript
const { merge } = require('webpack-merge'); const commonConfig = require('./rspack.common.js'); const devConfig = require('./rspack.dev.js'); const prodConfig = require('./rspack.prod.js'); module.exports = (env) => { const mode = env.mode || 'development'; if (mode === 'production') { return merge(commonConfig, prodConfig); } return merge(commonConfig, devConfig); };

2. Environment-specific Configuration

javascript
// rspack.dev.js module.exports = { mode: 'development', devtool: 'eval-cheap-module-source-map', devServer: { hot: true, port: 3000 } } // rspack.prod.js module.exports = { mode: 'production', devtool: 'source-map', optimization: { minimize: true } }

Environment Variable Best Practices

1. Sensitive Information Handling

javascript
// Don't hardcode sensitive information in code // ❌ Wrong const API_KEY = 'your-secret-key'; // ✅ Right const API_KEY = process.env.API_KEY; // Use .env.local to store sensitive information (not committed to version control) // .env.local API_KEY=your-secret-key

2. Environment Variable Validation

javascript
// Validate required environment variables const requiredEnvVars = ['API_URL', 'API_KEY']; requiredEnvVars.forEach(envVar => { if (!process.env[envVar]) { throw new Error(`Missing required environment variable: ${envVar}`); } });

3. Default Value Setting

javascript
// Set default values const apiUrl = process.env.API_URL || 'http://localhost:3000'; const timeout = parseInt(process.env.TIMEOUT || '5000', 10); const debug = process.env.DEBUG === 'true';

Environment Variables and Build

1. Conditional Build

javascript
module.exports = (env) => { const isProduction = env.mode === 'production'; return { mode: isProduction ? 'production' : 'development', plugins: [ new DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env.mode), 'process.env.IS_PRODUCTION': JSON.stringify(isProduction) }) ] }; };

2. Environment-specific Plugins

javascript
const isProduction = process.env.NODE_ENV === 'production'; const plugins = [ new DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }) ]; if (isProduction) { plugins.push( new TerserPlugin(), new CompressionPlugin() ); } module.exports = { plugins };

.env File Management

1. File Naming Conventions

shell
.env # Default values for all environments .env.local # Local overrides (not committed) .env.development # Development environment .env.test # Test environment .env.production # Production environment

2. .gitignore Configuration

shell
# Ignore all .env.local files .env.local .env.*.local # Can commit other environment configs .env.development .env.test .env.production

3. Environment Variable Priority

  1. Command line arguments
  2. .env.local
  3. .env.[mode].local
  4. .env.[mode]
  5. .env

Environment Variables and CI/CD

1. GitHub Actions

yaml
name: Build on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Node.js uses: actions/setup-node@v3 with: node-version: '18' - name: Install dependencies run: npm install - name: Build env: NODE_ENV: production API_URL: ${{ secrets.API_URL }} run: npm run build

2. Docker

dockerfile
# Dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . ARG NODE_ENV=production ARG API_URL ENV NODE_ENV=$NODE_ENV ENV API_URL=$API_URL RUN npm run build

Best Practices

  1. Security:

    • Don't hardcode sensitive information in code
    • Use .env.local to store local configuration
    • Use secrets in CI/CD
  2. Maintainability:

    • Create independent configuration files for different environments
    • Use clear variable naming
    • Provide default values
  3. Type Safety:

    • Provide type definitions for TypeScript projects
    • Validate environment variable validity
    • Handle missing environment variables
  4. Documentation:

    • Document all environment variables
    • Explain purpose of each variable
    • Provide example configurations

Rspack's environment variable management provides developers with flexible configuration methods. Through reasonable use of environment variables, you can easily manage configurations for different environments, improving development efficiency and code quality.

标签:Rspack