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-system.mddocs/

Environment System

Multi-environment build support allowing simultaneous builds for different targets with environment-specific configurations. Enables building for web, Node.js, and web workers with distinct settings and optimizations.

Capabilities

Environment Configuration

Define environment-specific configurations for different build targets.

/**
 * Environment-specific configuration interface
 */
interface EnvironmentConfig {
  /** Source code configuration for this environment */
  source?: SourceConfig;
  /** Build output configuration for this environment */
  output?: OutputConfig;
  /** HTML generation configuration for this environment */
  html?: HtmlConfig;
  /** Build tools configuration for this environment */
  tools?: ToolsConfig;
  /** Development configuration for this environment */
  dev?: DevConfig;
  /** Server configuration for this environment */
  server?: ServerConfig;
  /** Security configuration for this environment */
  security?: SecurityConfig;
  /** Performance configuration for this environment */
  performance?: PerformanceConfig;
  /** Module Federation configuration for this environment */
  moduleFederation?: ModuleFederationConfig;
}

/**
 * Main configuration with environments
 */
interface RsbuildConfig {
  /** Environment-specific configurations */
  environments?: Record<string, EnvironmentConfig>;
  // ... other global config properties
}

Usage Examples:

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

// Multi-environment configuration
export default defineConfig({
  // Global configuration applies to all environments
  source: {
    alias: {
      "@": "./src",
      "@utils": "./src/utils",
    },
  },
  
  // Environment-specific configurations
  environments: {
    // Web environment for browser
    web: {
      output: {
        target: "web",
        assetPrefix: "/static/",
      },
      html: {
        template: "./src/web.html",
        title: "Web App",
      },
      performance: {
        chunkSplit: {
          strategy: "split-by-experience",
        },
      },
    },
    
    // Node.js environment for server-side
    node: {
      output: {
        target: "node",
        filename: {
          js: "[name].cjs",
        },
      },
      tools: {
        rspack: {
          externals: {
            express: "commonjs express",
          },
        },
      },
    },
    
    // Web worker environment
    worker: {
      output: {
        target: "web-worker",
      },
      source: {
        entry: {
          worker: "./src/worker.ts",
        },
      },
    },
    
    // Mobile-optimized web environment
    mobile: {
      output: {
        target: "web",
        assetPrefix: "https://cdn.example.com/mobile/",
      },
      performance: {
        chunkSplit: {
          strategy: "all-in-one",
        },
        removeConsole: true,
      },
      html: {
        template: "./src/mobile.html",
        meta: {
          viewport: "width=device-width, initial-scale=1.0, user-scalable=no",
        },
      },
    },
  },
});

Environment Context

Runtime context information provided to plugins and hooks for each environment.

/**
 * Environment context provided during build process
 */
interface EnvironmentContext {
  /** Environment name */
  name: string;
  /** Environment index in build order */
  index: number;
  /** Entry point configuration */
  entry: RsbuildEntry;
  /** HTML file paths mapping */
  htmlPaths: Record<string, string>;
  /** Output directory path */
  distPath: string;
  /** Browser compatibility targets */
  browserslist: string[];
  /** Normalized environment configuration */
  config: NormalizedEnvironmentConfig;
  /** WebSocket token for dev server */
  webSocketToken: string;
}

/**
 * Normalized environment configuration with defaults applied
 */
interface NormalizedEnvironmentConfig {
  source: NormalizedSourceConfig;
  output: NormalizedOutputConfig;
  html: NormalizedHtmlConfig;
  tools: NormalizedToolsConfig;
  dev: NormalizedDevConfig;
  server: NormalizedServerConfig;
  security: NormalizedSecurityConfig;
  performance: NormalizedPerformanceConfig;
  moduleFederation: NormalizedModuleFederationConfig;
}

Environment-Specific Hooks

Hooks that receive environment context for environment-aware processing.

/**
 * Hook called before compilation for each environment
 */
type OnBeforeEnvironmentCompileFn = (params: {
  environment: EnvironmentContext;
}) => void | Promise<void>;

/**
 * Hook called after compilation for each environment
 */
type OnAfterEnvironmentCompileFn = (params: {
  environment: EnvironmentContext;
  stats: any;
}) => void | Promise<void>;

Hook Usage Examples:

const multiEnvPlugin = (): RsbuildPlugin => ({
  name: "multi-env-plugin",
  setup(api) {
    api.onBeforeEnvironmentCompile(({ environment }) => {
      console.log(`Starting compilation for ${environment.name}`);
      
      // Environment-specific logic
      if (environment.name === "node") {
        console.log("Configuring for Node.js target");
      } else if (environment.name === "web") {
        console.log("Configuring for web target");
      }
    });
    
    api.onAfterEnvironmentCompile(({ environment, stats }) => {
      console.log(`Completed compilation for ${environment.name}`);
      
      if (stats.hasErrors()) {
        console.error(`Errors in ${environment.name} build`);
      }
    });
  },
});

Environment-Aware Configuration

Modify configuration based on environment context.

/**
 * Modify environment configuration hook
 */
type ModifyEnvironmentConfigFn = (
  config: EnvironmentConfig,
  utils: ModifyEnvironmentConfigUtils
) => EnvironmentConfig | void | Promise<EnvironmentConfig | void>;

interface ModifyEnvironmentConfigUtils {
  /** Environment name */
  name: string;
  /** Configuration merging utility */
  mergeConfig: (config: EnvironmentConfig) => EnvironmentConfig;
}

Configuration Examples:

const envConfigPlugin = (): RsbuildPlugin => ({
  name: "env-config-plugin",
  setup(api) {
    api.modifyEnvironmentConfig((config, { name, mergeConfig }) => {
      // Environment-specific modifications
      switch (name) {
        case "web":
          return mergeConfig(config, {
            output: {
              assetPrefix: "/web-assets/",
            },
            performance: {
              bundleAnalyze: process.env.ANALYZE === "true",
            },
          });
          
        case "node":
          return mergeConfig(config, {
            output: {
              externals: {
                // Mark Node.js modules as external
                fs: "commonjs fs",
                path: "commonjs path",
                os: "commonjs os",
              },
            },
          });
          
        case "mobile":
          return mergeConfig(config, {
            performance: {
              removeConsole: true,
              chunkSplit: {
                strategy: "all-in-one",
              },
            },
          });
          
        default:
          return config;
      }
    });
  },
});

Build Target Types

/**
 * Available build targets
 */
type RsbuildTarget = 'web' | 'node' | 'web-worker';

/**
 * Target-specific configuration
 */
interface OutputConfig {
  /** Build target platform(s) */
  target?: RsbuildTarget | RsbuildTarget[];
  // ... other output options
}

Target Characteristics:

  • web: Browser environment with DOM, Web APIs, and module loading
  • node: Node.js environment with Node.js APIs and CommonJS modules
  • web-worker: Web Worker environment with limited APIs and no DOM

Environment Selection

Control which environments to build during development or production.

interface CreateRsbuildOptions {
  /** Specific environments to build */
  environment?: string[];
  // ... other options
}

Usage Examples:

// Build only specific environments
const rsbuild = await createRsbuild({
  rsbuildConfig: config,
  environment: ["web", "mobile"], // Only build web and mobile
});

// Build all environments (default)
const rsbuildAll = await createRsbuild({
  rsbuildConfig: config,
  // Builds all defined environments
});

// Environment-specific development
if (process.env.TARGET === "mobile") {
  rsbuild = await createRsbuild({
    rsbuildConfig: config,
    environment: ["mobile"],
  });
}

Environment-Specific Entry Points

Different entry points for different environments.

export default defineConfig({
  environments: {
    web: {
      source: {
        entry: {
          index: "./src/web/index.ts",
          about: "./src/web/about.ts",
        },
      },
    },
    
    node: {
      source: {
        entry: {
          server: "./src/server/index.ts",
          worker: "./src/server/worker.ts",
        },
      },
    },
    
    worker: {
      source: {
        entry: {
          "service-worker": "./src/workers/service-worker.ts",
          "web-worker": "./src/workers/web-worker.ts",
        },
      },
    },
  },
});

Environment-Specific HTML

Different HTML templates and configurations per environment.

export default defineConfig({
  environments: {
    web: {
      html: {
        template: "./src/templates/web.html",
        title: "Web Application",
        meta: {
          description: "Full-featured web application",
        },
      },
    },
    
    mobile: {
      html: {
        template: "./src/templates/mobile.html",
        title: "Mobile App",
        meta: {
          viewport: "width=device-width, initial-scale=1.0, user-scalable=no",
          "mobile-web-app-capable": "yes",
        },
      },
    },
    
    // Node.js environments typically don't need HTML
    node: {
      html: false, // Disable HTML generation
    },
  },
});

Performance Optimization by Environment

Environment-specific performance optimizations.

export default defineConfig({
  environments: {
    web: {
      performance: {
        chunkSplit: {
          strategy: "split-by-experience",
        },
        preload: true,
        prefetch: true,
      },
    },
    
    mobile: {
      performance: {
        chunkSplit: {
          strategy: "all-in-one", // Single bundle for mobile
        },
        removeConsole: true,
        bundleAnalyze: false,
      },
    },
    
    node: {
      performance: {
        chunkSplit: {
          strategy: "all-in-one", // Single server bundle
        },
        removeConsole: false, // Keep console for server logging
      },
    },
  },
});

Development Server per Environment

Environment-specific development server configuration.

export default defineConfig({
  environments: {
    web: {
      server: {
        port: 3000,
        open: true,
      },
      dev: {
        hmr: true,
      },
    },
    
    mobile: {
      server: {
        port: 3001,
        host: "0.0.0.0", // Allow mobile device access
      },
      dev: {
        client: {
          overlay: {
            warnings: false, // Less intrusive on mobile
          },
        },
      },
    },
    
    // Node.js environments typically don't need dev server
    node: {
      server: false, // Disable dev server
    },
  },
});

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