CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webpack

A comprehensive module bundler and build tool for JavaScript applications with advanced optimization and plugin system.

Pending
Overview
Eval results
Files

configuration.mddocs/

Configuration API

Webpack's configuration API provides comprehensive configuration processing, validation, and default value application. It handles complex configuration normalization, validation against schemas, and application of intelligent defaults based on environment and build mode.

Capabilities

Configuration Validation

Validates webpack configuration objects against the internal schema to ensure correctness and provide helpful error messages.

/**
 * Validates webpack configuration against schema
 * @param options - Configuration object or array of configurations to validate
 * @throws ValidationError if configuration is invalid
 */
function validate(options: Configuration | MultiConfiguration): void;

/**
 * General schema validation utility for custom schemas
 * @param schema - JSON schema to validate against
 * @param options - Object to validate
 * @param optionsName - Name of the options for error messages
 * @throws ValidationError if validation fails
 */
function validateSchema(
  schema: JSONSchema7, 
  options: any, 
  optionsName: string
): void;

Usage Examples:

const webpack = require("webpack");

try {
  webpack.validate({
    entry: "./src/index.js",
    output: {
      filename: "bundle.js",
      path: "/invalid/path" // This might trigger validation warnings
    },
    mode: "production"
  });
  console.log("Configuration is valid!");
} catch (error) {
  console.error("Configuration validation failed:", error.message);
}

Configuration Normalization

Normalizes raw webpack configuration into a standardized internal format, handling various input formats and shorthand notations.

/**
 * Normalizes webpack configuration options
 * @param options - Raw configuration options in any supported format
 * @returns Normalized configuration with consistent structure
 */
function config.getNormalizedWebpackOptions(options: Configuration): WebpackOptionsNormalized;

Usage Examples:

const { getNormalizedWebpackOptions } = require("webpack/lib/config/normalization");

// Normalize shorthand entry format
const rawConfig = {
  entry: "./src/index.js", // String shorthand
  mode: "development"
};

const normalized = getNormalizedWebpackOptions(rawConfig);
// normalized.entry is now: { main: { import: ["./src/index.js"] } }

Configuration Defaults

Applies intelligent default values based on mode, target, and other configuration options.

/**
 * Applies default configuration values to normalized options
 * @param options - Normalized webpack options
 * @returns Configuration with defaults applied
 */
function config.applyWebpackOptionsDefaults(options: WebpackOptionsNormalized): WebpackOptionsNormalized;

Usage Examples:

const { applyWebpackOptionsDefaults } = require("webpack/lib/config/defaults");
const { getNormalizedWebpackOptions } = require("webpack/lib/config/normalization");

const rawConfig = { entry: "./src/index.js", mode: "production" };
const normalized = getNormalizedWebpackOptions(rawConfig);
const withDefaults = applyWebpackOptionsDefaults(normalized);

// withDefaults now includes default optimization settings, output paths, etc.

Main Configuration Interface

The comprehensive webpack configuration interface supporting all build scenarios from simple applications to complex multi-target builds.

interface Configuration {
  /** Entry points for the application */
  entry?: string | string[] | Entry | EntryFunc;
  
  /** Output configuration for generated bundles */
  output?: Output;
  
  /** Build mode affecting defaults and optimizations */
  mode?: "development" | "production" | "none";
  
  /** Module processing configuration */
  module?: ModuleOptions;
  
  /** Array of webpack plugins */
  plugins?: WebpackPluginInstance[];
  
  /** Module resolution configuration */
  resolve?: ResolveOptions;
  
  /** Optimization configuration */
  optimization?: OptimizationOptions;
  
  /** Development tool for source maps */
  devtool?: string | false;
  
  /** Build target environment */
  target?: string | string[] | false;
  
  /** External dependencies configuration */
  externals?: Externals;
  
  /** Performance hints and limits */
  performance?: Performance | false;
  
  /** Node.js polyfills configuration */
  node?: Node | false;
  
  /** Statistics output configuration */
  stats?: StatsOptions | string | boolean;
  
  /** Watch mode configuration */
  watch?: boolean;
  
  /** Watch options */
  watchOptions?: WatchOptions;
  
  /** Development server configuration */
  devServer?: DevServerOptions;
  
  /** Caching configuration */
  cache?: CacheOptions | boolean;
  
  /** Infrastructure logging configuration */
  infrastructureLogging?: InfrastructureLogging;
  
  /** Snapshot configuration for filesystem watching */
  snapshot?: SnapshotOptions;
  
  /** Experimental features */
  experiments?: Experiments;
  
  /** Context directory for resolving entries */
  context?: string;
  
  /** Dependency configuration */
  dependencies?: string[];
  
  /** Environment name for conditional configuration */
  name?: string;
  
  /** Bail on first error in multi-compiler mode */
  bail?: boolean;
  
  /** Profile compilation for performance analysis */
  profile?: boolean;
  
  /** Parallelism limit for processing */
  parallelism?: number;
  
  /** Record input/output files for persistent caching */
  recordsPath?: string;
  recordsInputPath?: string;
  recordsOutputPath?: string;
}

/** Multi-configuration for parallel builds */
type MultiConfiguration = Configuration[];

/** Function-based configuration for dynamic setups */
type ConfigurationFunc = (
  env: any, 
  argv: any
) => Configuration | MultiConfiguration | Promise<Configuration | MultiConfiguration>;

Entry Configurations

Flexible entry point configuration supporting various application architectures.

/** Entry point configuration types */
type Entry = string | string[] | EntryObject | EntryFunc;

/** Object-based entry configuration for multiple entry points */
interface EntryObject {
  [name: string]: string | string[] | EntryDescription;
}

/** Detailed entry point description */
interface EntryDescription {
  /** Import modules for this entry */
  import: string | string[];
  
  /** Runtime chunk name for this entry */
  runtime?: string | false;
  
  /** Public path for this entry's assets */
  publicPath?: string | ((pathData: PathData) => string);
  
  /** Base URI for this entry */
  baseUri?: string;
  
  /** Chunk loading type for this entry */
  chunkLoading?: ChunkLoadingType | false;
  
  /** Async chunks flag */
  asyncChunks?: boolean;
  
  /** WASM loading type */
  wasmLoading?: WasmLoadingType | false;
  
  /** Entry filename template */
  filename?: string | ((pathData: PathData) => string);
  
  /** Library configuration for this entry */
  library?: LibraryOptions;
  
  /** Depends on other entries */
  dependOn?: string | string[];
}

/** Dynamic entry configuration */
type EntryFunc = () => Entry | Promise<Entry>;

Usage Examples:

// String entry (single file)
module.exports = {
  entry: "./src/index.js"
};

// Array entry (multiple files, single chunk)
module.exports = {
  entry: ["./src/polyfills.js", "./src/index.js"]
};

// Object entry (multiple named chunks)
module.exports = {
  entry: {
    main: "./src/index.js",
    vendor: "./src/vendor.js",
    admin: "./src/admin/index.js"
  }
};

// Detailed entry descriptions
module.exports = {
  entry: {
    main: {
      import: "./src/index.js",
      runtime: "main-runtime",
      dependOn: "shared"
    },
    shared: {
      import: "./src/shared.js",
      runtime: false // No runtime chunk
    },
    admin: {
      import: "./src/admin/index.js",
      filename: "admin/[name].[contenthash].js",
      chunkLoading: "jsonp"
    }
  }
};

// Dynamic entry function
module.exports = {
  entry: () => {
    return {
      main: "./src/index.js",
      // Conditionally add entries based on environment
      ...(process.env.NODE_ENV === "development" && {
        dev: "./src/dev-tools.js"
      })
    };
  }
};

Output Configurations

Comprehensive output configuration for controlling generated bundle characteristics.

interface Output {
  /** Filename template for entry chunks */
  filename?: string | ((pathData: PathData) => string);
  
  /** Output directory path */
  path?: string;
  
  /** Public URL path for assets */
  publicPath?: string | ((pathData: PathData) => string);
  
  /** Filename template for non-entry chunks */
  chunkFilename?: string | ((pathData: PathData) => string);
  
  /** Filename template for async WASM modules */
  webassemblyModuleFilename?: string | ((pathData: PathData) => string);
  
  /** Asset module filename template */
  assetModuleFilename?: string | ((pathData: PathData) => string);
  
  /** Library configuration for UMD/library builds */
  library?: LibraryOptions;
  
  /** Global object name for library builds */
  globalObject?: string;
  
  /** Import function name for ESM builds */
  importFunctionName?: string;
  
  /** Import meta name for ESM builds */
  importMetaName?: string;
  
  /** Clean output directory before build */
  clean?: boolean | CleanOptions;
  
  /** Compare before emit to avoid unnecessary writes */
  compareBeforeEmit?: boolean;
  
  /** Cross-origin loading configuration */
  crossOriginLoading?: string | false;
  
  /** Charset for script tags */
  charset?: boolean;
  
  /** Enable/disable source map filename info */
  sourceMapFilename?: string;
  
  /** Hotupdate main filename */
  hotUpdateMainFilename?: string;
  
  /** Hotupdate chunk filename */
  hotUpdateChunkFilename?: string;
  
  /** Script type for entry scripts */
  scriptType?: "text/javascript" | "module" | false;
  
  /** Unique name for HMR */
  uniqueName?: string;
  
  /** Chunk loading global name */
  chunkLoadingGlobal?: string;
  
  /** Enable trusted types policy */
  trustedTypes?: TrustedTypesOptions | true;
  
  /** Hash function for content hashing */
  hashFunction?: string | typeof Hash;
  
  /** Hash digest type */
  hashDigest?: string;
  
  /** Hash digest length */
  hashDigestLength?: number;
  
  /** Hash salt */
  hashSalt?: string;
  
  /** Strict module exception handling */
  strictModuleExceptionHandling?: boolean;
  
  /** Strict module error handling */
  strictModuleErrorHandling?: boolean;
  
  /** Module loading type */
  module?: boolean;
  
  /** Environment configuration */
  environment?: Environment;
  
  /** IIFE (Immediately Invoked Function Expression) wrapper */
  iife?: boolean;
}

/** Library output configuration */
interface LibraryOptions {
  /** Library name */
  name?: string | string[] | LibraryName;
  
  /** Library type (UMD, CommonJS, etc.) */
  type?: LibraryType;
  
  /** Export property to expose */
  export?: string | string[];
  
  /** UMD named define */
  umdNamedDefine?: boolean;
  
  /** Auxiliary comment */
  auxiliaryComment?: string | LibraryAuxiliaryComment;
}

Usage Examples:

module.exports = {
  output: {
    // Basic filename with content hash
    filename: "[name].[contenthash].js",
    
    // Output to dist directory
    path: path.resolve(__dirname, "dist"),
    
    // Public path for CDN deployment
    publicPath: "https://cdn.example.com/assets/",
    
    // Chunk filename pattern
    chunkFilename: "[name].[contenthash].chunk.js",
    
    // Asset filename pattern
    assetModuleFilename: "assets/[name].[hash][ext]",
    
    // Clean output directory
    clean: true
  }
};

// Library build configuration
module.exports = {
  output: {
    filename: "my-library.js",
    path: path.resolve(__dirname, "dist"),
    library: {
      name: "MyLibrary",
      type: "umd"
    },
    globalObject: "this"
  }
};

// Dynamic public path
module.exports = {
  output: {
    filename: "[name].js",
    publicPath: (pathData) => {
      return process.env.NODE_ENV === "production" 
        ? "/prod-assets/" 
        : "/dev-assets/";
    }
  }
};

Module Configurations

Module processing configuration including loaders, parsers, and generators.

interface ModuleOptions {
  /** Rules for processing different file types */
  rules?: RuleSetRule[];
  
  /** No parsing rules */
  noParse?: string | RegExp | ((content: string) => boolean) | Array<string | RegExp | ((content: string) => boolean)>;
  
  /** Unknown context request handling */
  unknownContextRequest?: string;
  
  /** Unknown context recursive flag */
  unknownContextRecursive?: boolean;
  
  /** Unknown context regexp */
  unknownContextRegExp?: RegExp;
  
  /** Unknown context critical flag */
  unknownContextCritical?: boolean;
  
  /** Expression context request handling */
  exprContextRequest?: string;
  
  /** Expression context recursive flag */
  exprContextRecursive?: boolean;
  
  /** Expression context regexp */
  exprContextRegExp?: RegExp;
  
  /** Expression context critical flag */
  exprContextCritical?: boolean;
  
  /** Wrapped context request handling */
  wrappedContextRequest?: string;
  
  /** Wrapped context recursive flag */
  wrappedContextRecursive?: boolean;
  
  /** Wrapped context regexp */
  wrappedContextRegExp?: RegExp;
  
  /** Wrapped context critical flag */
  wrappedContextCritical?: boolean;
  
  /** Strict export presence */
  strictExportPresence?: boolean;
  
  /** Strict this context on imports */
  strictThisContextOnImports?: boolean;
  
  /** Unsafe cache for module processing */
  unsafeCache?: boolean | ((module: Module) => boolean);
  
  /** Default rules applied to all modules */
  defaultRules?: RuleSetRule[];
  
  /** Parser options by module type */
  parser?: ParserOptionsByModuleType;
  
  /** Generator options by module type */
  generator?: GeneratorOptionsByModuleType;
}

/** Rule for processing modules */
interface RuleSetRule {
  /** Test condition for matching files */
  test?: RuleSetCondition;
  
  /** Include condition */
  include?: RuleSetCondition;
  
  /** Exclude condition */
  exclude?: RuleSetCondition;
  
  /** Resource condition (combines test/include/exclude) */
  resource?: RuleSetCondition;
  
  /** Issuer condition (module that imports this) */
  issuer?: RuleSetCondition;
  
  /** Dependency type condition */
  dependency?: RuleSetCondition;
  
  /** Module layer */
  layer?: string;
  
  /** Loaders to apply */
  use?: RuleSetUse;
  
  /** Alias for use */
  loader?: string;
  
  /** Options for single loader */
  options?: any;
  
  /** Module type override */
  type?: string;
  
  /** Parser options for this rule */
  parser?: ParserOptions;
  
  /** Generator options for this rule */
  generator?: GeneratorOptions;
  
  /** Resource fragment condition */
  resourceFragment?: RuleSetCondition;
  
  /** Resource query condition */
  resourceQuery?: RuleSetCondition;
  
  /** Resolve configuration for this rule */
  resolve?: ResolveOptions;
  
  /** Side effects flag */
  sideEffects?: boolean;
  
  /** Nested rules */
  rules?: RuleSetRule[];
  
  /** Alternative rules (oneOf) */
  oneOf?: RuleSetRule[];
  
  /** Enforcement stage */
  enforce?: "pre" | "post";
  
  /** Description for debugging */
  descriptionData?: { [k: string]: any };
  
  /** Schema version */
  schema?: any;
  
  /** Mimetype condition */
  mimetype?: RuleSetCondition;
}

/** Use configuration for loaders */
type RuleSetUse = 
  | RuleSetUseItem 
  | RuleSetUseItem[] 
  | ((info: UseInfo) => RuleSetUseItem | RuleSetUseItem[]);

/** Individual loader configuration */
interface RuleSetUseItem {
  /** Loader name or path */
  loader?: string;
  
  /** Loader options */
  options?: any;
  
  /** Loader identifier */
  ident?: string;
  
  /** Type of use item */
  type?: string;
}

/** Condition types for matching */
type RuleSetCondition = 
  | string 
  | RegExp 
  | ((value: string) => boolean)
  | RuleSetLogicalConditions
  | RuleSetCondition[];

interface RuleSetLogicalConditions {
  /** AND condition */
  and?: RuleSetCondition[];
  
  /** OR condition */
  or?: RuleSetCondition[];
  
  /** NOT condition */
  not?: RuleSetCondition;
}

Usage Examples:

module.exports = {
  module: {
    rules: [
      // JavaScript/TypeScript files
      {
        test: /\.(js|ts|tsx)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env", "@babel/preset-react"]
            }
          }
        ]
      },
      
      // CSS files with CSS modules
      {
        test: /\.css$/,
        include: path.resolve(__dirname, "src"),
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              modules: true,
              localIdentName: "[name]__[local]__[hash:base64:5]"
            }
          }
        ]
      },
      
      // Images and assets
      {
        test: /\.(png|jpg|gif|svg)$/,
        type: "asset/resource",
        generator: {
          filename: "images/[name].[hash][ext]"
        }
      },
      
      // Fonts
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        type: "asset/inline"
      },
      
      // Conditional loader based on issuer
      {
        test: /\.scss$/,
        issuer: {
          and: [/\.js$/, { not: /node_modules/ }]
        },
        use: ["style-loader", "css-loader", "sass-loader"]
      },
      
      // Dynamic loader configuration
      {
        test: /\.js$/,
        use: (info) => {
          if (info.resource.includes("legacy")) {
            return ["babel-loader"];
          }
          return ["swc-loader"];
        }
      }
    ],
    
    // Skip parsing for known libraries
    noParse: /jquery|lodash/,
    
    // Strict export presence checking
    strictExportPresence: true
  }
};

Resolve Configurations

Module resolution configuration for finding and processing imports.

interface ResolveOptions {
  /** Module resolution algorithm */
  resolverOptions?: ResolverOptions;
  
  /** Alias mapping for module names */
  alias?: AliasOptions;
  
  /** Fallback mapping */
  fallback?: AliasOptions;
  
  /** Module directories to search */
  modules?: string[];
  
  /** File extensions to try */
  extensions?: string[];
  
  /** Main fields to check in package.json */
  mainFields?: string[];
  
  /** Main files to look for */
  mainFiles?: string[];
  
  /** Description files to read */
  descriptionFiles?: string[];
  
  /** Enforce extension requirement */
  enforceExtension?: boolean;
  
  /** Exports fields to use */
  exportsFields?: string[];
  
  /** Imports fields to use */
  importsFields?: string[];
  
  /** Condition names for exports/imports */
  conditionNames?: string[];
  
  /** Symbol links handling */
  symlinks?: boolean;
  
  /** Cache resolve results */
  cache?: boolean;
  
  /** Plugins for custom resolution */
  plugins?: ResolvePluginInstance[];
  
  /** Prefer relative paths */
  preferRelative?: boolean;
  
  /** Prefer absolute paths */
  preferAbsolute?: boolean;
  
  /** Restrictions on resolved paths */
  restrictions?: (string | RegExp)[];
  
  /** Roots for absolute resolution */
  roots?: string[];
  
  /** Unsafe cache for performance */
  unsafeCache?: boolean | object;
  
  /** Full specified flag */
  fullySpecified?: boolean;
  
  /** By dependency type resolution */
  byDependency?: { [k: string]: ResolveOptions };
}

/** Alias configuration */
type AliasOptions = 
  | { [key: string]: string | false | string[] }
  | AliasOption[];

interface AliasOption {
  /** Alias name */
  name: string;
  
  /** Alias target */
  alias: string | false | string[];
  
  /** Only replace if it's the exact match */
  onlyModule?: boolean;
}

Usage Examples:

module.exports = {
  resolve: {
    // File extensions to resolve automatically
    extensions: [".js", ".jsx", ".ts", ".tsx", ".json"],
    
    // Alias for shorter imports
    alias: {
      "@": path.resolve(__dirname, "src"),
      "@components": path.resolve(__dirname, "src/components"),
      "@utils": path.resolve(__dirname, "src/utils"),
      // Exclude a module
      "fs": false
    },
    
    // Module directories
    modules: ["node_modules", path.resolve(__dirname, "src")],
    
    // Main fields for package.json
    mainFields: ["browser", "module", "main"],
    
    // Main files to try
    mainFiles: ["index"],
    
    // Fallbacks for Node.js modules in browser
    fallback: {
      "path": require.resolve("path-browserify"),
      "fs": false,
      "crypto": require.resolve("crypto-browserify")
    },
    
    // Condition names for exports field
    conditionNames: ["import", "module", "browser", "default"],
    
    // By dependency type configuration
    byDependency: {
      esm: {
        fullySpecified: true
      },
      commonjs: {
        fullySpecified: false
      }
    }
  }
};

Optimization Configurations

Advanced optimization settings for production builds and performance.

interface OptimizationOptions {
  /** Enable/disable minimization */
  minimize?: boolean;
  
  /** Minimizer plugins */
  minimizer?: WebpackPluginInstance[];
  
  /** Split chunks configuration */
  splitChunks?: SplitChunksOptions | false;
  
  /** Runtime chunk configuration */
  runtimeChunk?: RuntimeChunkOptions;
  
  /** Bail on first error */
  emitOnErrors?: boolean;
  
  /** Module concatenation (scope hoisting) */
  concatenateModules?: boolean;
  
  /** Side effects detection */
  sideEffects?: boolean | "flag";
  
  /** Used exports detection (tree shaking) */
  usedExports?: boolean | "global";
  
  /** Provided exports detection */
  providedExports?: boolean;
  
  /** Optimization bailout reasons */
  flagIncludedChunks?: boolean;
  
  /** Optimize module IDs */
  moduleIds?: ModuleIdsType;
  
  /** Optimize chunk IDs */
  chunkIds?: ChunkIdsType;
  
  /** Remove available modules */
  removeAvailableModules?: boolean;
  
  /** Remove empty chunks */
  removeEmptyChunks?: boolean;
  
  /** Merge duplicate chunks */
  mergeDuplicateChunks?: boolean;
  
  /** Mangle webpack runtime */
  mangleWasmImports?: boolean;
  
  /** Portables records */
  portableRecords?: boolean;
  
  /** Real content hash */
  realContentHash?: boolean;
  
  /** Inner graph analysis */
  innerGraph?: boolean;
  
  /** Mangle exports */
  mangleExports?: boolean | "deterministic" | "size";
  
  /** Node.js environment detection */
  nodeEnv?: string | false;
}

/** Split chunks configuration */
interface SplitChunksOptions {
  /** Chunks to split */
  chunks?: "all" | "async" | "initial" | ((chunk: Chunk) => boolean);
  
  /** Minimum chunk size */
  minSize?: number;
  
  /** Minimum remaining size after split */
  minRemainingSize?: number;
  
  /** Minimum chunk size for development */
  minSizeReduction?: number;
  
  /** Maximum async requests */
  maxAsyncRequests?: number;
  
  /** Maximum initial requests */
  maxInitialRequests?: number;
  
  /** Enforce size limits */
  enforceSizeThreshold?: number;
  
  /** Automatic name generation */
  automaticNameDelimiter?: string;
  
  /** Cache groups configuration */
  cacheGroups?: CacheGroupsOptions;
  
  /** Default name */
  name?: string | false | SplitChunksNameFunction;
  
  /** Filename template */
  filename?: string | SplitChunksFilenameFunction;
  
  /** Hide path info */
  hidePathInfo?: boolean;
  
  /** Maximum size */
  maxSize?: number;
  
  /** Maximum async size */
  maxAsyncSize?: number;
  
  /** Maximum initial size */
  maxInitialSize?: number;
  
  /** Used exports */
  usedExports?: boolean;
}

type RuntimeChunkOptions = 
  | "single" 
  | "multiple" 
  | boolean
  | { name?: string | RuntimeChunkFunction };

type ModuleIdsType = "natural" | "named" | "deterministic" | "size" | false;
type ChunkIdsType = "natural" | "named" | "deterministic" | "size" | "total-size" | false;

Usage Examples:

module.exports = {
  optimization: {
    // Enable minimization in production
    minimize: true,
    
    // Custom minimizers
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true
          }
        }
      })
    ],
    
    // Split chunks configuration
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        // Vendor chunk for node_modules
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all",
          priority: 10
        },
        
        // Common chunk for shared modules
        common: {
          name: "common",
          minChunks: 2,
          chunks: "all",
          priority: 5,
          reuseExistingChunk: true
        }
      }
    },
    
    // Extract runtime to separate chunk
    runtimeChunk: "single",
    
    // Tree shaking configuration
    usedExports: true,
    sideEffects: false,
    
    // Module concatenation for better performance
    concatenateModules: true,
    
    // Deterministic module IDs for better caching
    moduleIds: "deterministic",
    chunkIds: "deterministic"
  }
};

DevTool Options

Source map generation configuration for debugging support.

/** DevTool configuration for source maps */
type DevTool = 
  | false
  | "eval"
  | "eval-cheap-source-map"
  | "eval-cheap-module-source-map"
  | "eval-source-map"
  | "cheap-source-map"
  | "cheap-module-source-map"
  | "source-map"
  | "inline-cheap-source-map"
  | "inline-cheap-module-source-map"
  | "inline-source-map"
  | "eval-nosources-cheap-source-map"
  | "eval-nosources-cheap-module-source-map"
  | "eval-nosources-source-map"
  | "inline-nosources-cheap-source-map"
  | "inline-nosources-cheap-module-source-map"
  | "inline-nosources-source-map"
  | "nosources-cheap-source-map"
  | "nosources-cheap-module-source-map"
  | "nosources-source-map"
  | "hidden-cheap-source-map"
  | "hidden-cheap-module-source-map"
  | "hidden-source-map"
  | "hidden-nosources-cheap-source-map"
  | "hidden-nosources-cheap-module-source-map"
  | "hidden-nosources-source-map";

Usage Examples:

module.exports = {
  // Development: fast rebuilds with good debugging
  devtool: process.env.NODE_ENV === "development" 
    ? "eval-cheap-module-source-map" 
    : "source-map",
    
  // Alternative conditional configuration
  devtool: (() => {
    if (process.env.NODE_ENV === "production") {
      return "source-map"; // High quality for production debugging
    }
    if (process.env.NODE_ENV === "development") {
      return "eval-source-map"; // Fast rebuilds for development
    }
    return false; // No source maps for other environments
  })()
};

Target Options

Build target configuration for different environments and platforms.

/** Target environment configuration */
type Target = 
  | string 
  | string[] 
  | false
  | TargetFunction;

type TargetFunction = (compiler: Compiler) => void;

/** Common target values */
type TargetValues = 
  | "web"                    // Web browsers (default)
  | "webworker"             // Web Workers
  | "node"                  // Node.js
  | "async-node"            // Node.js with async chunk loading
  | "node-webkit"           // NW.js
  | "nwjs"                  // NW.js (alias)
  | "electron-main"         // Electron main process
  | "electron-renderer"     // Electron renderer process
  | "electron-preload"      // Electron preload scripts
  | "browserslist"          // Use browserslist configuration
  | "es5"                   // ES5 compatibility
  | "es2015"                // ES2015 compatibility
  | "es2017"                // ES2017 compatibility
  | "es2020"                // ES2020 compatibility

Usage Examples:

// Single target
module.exports = {
  target: "node"
};

// Multiple targets for universal builds
module.exports = {
  target: ["web", "es5"]
};

// Browserslist-based targeting
module.exports = {
  target: "browserslist"
};

// Function-based target for custom configuration
module.exports = {
  target: (compiler) => {
    compiler.options.output.globalObject = "this";
  }
};

// Environment-specific targets
module.exports = {
  target: process.env.ELECTRON_ENV === "main" 
    ? "electron-main" 
    : "electron-renderer"
};

External Configurations

External dependencies configuration for excluding modules from bundling.

/** External dependencies configuration */
type Externals = 
  | string 
  | RegExp
  | ExternalItemObjectKnown
  | ExternalItemObjectUnknown  
  | ExternalItemFunctionData
  | ExternalItem[]
  | (ExternalItemFunctionData | ExternalItemFunctionPromise | ExternalItemValue);

/** External item as object with different module formats */
interface ExternalItemObjectKnown {
  /** AMD module format */
  amd?: string;
  
  /** CommonJS module format */
  commonjs?: string;
  
  /** CommonJS2 module format */
  commonjs2?: string;
  
  /** Root (global) variable */
  root?: string | string[];
  
  /** Import statement */
  import?: string;
  
  /** Variable name */
  var?: string;
  
  /** Module format */
  module?: string;
  
  /** UMD format */
  umd?: string | ExternalItemObjectKnownUmd;
  
  /** JSONP format */
  jsonp?: string;
  
  /** System.js format */
  system?: string;
  
  /** Promise-based external */
  promise?: string;
  
  /** Script source URL */
  script?: string | ExternalItemObjectKnownScript;
}

/** Function-based external resolution */
type ExternalItemFunction = (
  data: ExternalItemFunctionData,
  callback: (err?: Error | null, result?: ExternalItemValue) => void
) => void;

interface ExternalItemFunctionData {
  /** Module context */
  context?: string;
  
  /** Dependency type */
  dependencyType?: string;
  
  /** Module request */
  request?: string;
  
  /** Context info */
  contextInfo?: ModuleInfo;
  
  /** Get resolve function */
  getResolve?: (options?: ResolveOptions) => ResolveFunction;
}

Usage Examples:

module.exports = {
  // Simple string externals
  externals: {
    "jquery": "jQuery",
    "lodash": "_"
  },
  
  // RegExp-based externals
  externals: [
    /^@company\/.+$/,  // Exclude all @company packages
    /^aws-sdk/         // Exclude AWS SDK
  ],
  
  // Multiple formats for different environments
  externals: {
    "react": {
      root: "React",
      commonjs2: "react",
      commonjs: "react", 
      amd: "react",
      umd: "react"
    }
  },
  
  // Function-based externals for dynamic resolution
  externals: [
    (data, callback) => {
      // Externalize requests that start with "electron"
      if (/^electron/.test(data.request)) {
        return callback(null, "commonjs " + data.request);
      }
      callback();
    }
  ],
  
  // Node.js externals (exclude all node_modules)
  externals: [
    ({ context, request }, callback) => {
      if (/^[a-z@][a-z0-9\-\/]*$/.test(request)) {
        return callback(null, "commonjs " + request);
      }
      callback();
    }
  ]
};

Watch Options

File watching configuration for development builds.

interface WatchOptions {
  /** Delay before rebuilding after change */
  aggregateTimeout?: number;
  
  /** Enable polling for file changes */
  poll?: boolean | number;
  
  /** Files/directories to ignore */
  ignored?: string | RegExp | string[];
  
  /** Follow symbolic links */
  followSymlinks?: boolean;
  
  /** Stdin end triggers exit */
  stdin?: boolean;
}

interface Watching {
  /** Stop watching */
  close(callback: (err?: Error) => void): void;
  
  /** Invalidate current build */
  invalidate(callback?: (err?: Error) => void): void;
  
  /** Suspend watching */
  suspend(): void;
  
  /** Resume watching */
  resume(): void;
}

Usage Examples:

const webpack = require("webpack");
const config = require("./webpack.config.js");

const compiler = webpack(config);

// Watch with options
const watching = compiler.watch({
  // Wait 300ms before rebuilding
  aggregateTimeout: 300,
  
  // Poll every second for changes (useful in containers)
  poll: 1000,
  
  // Ignore node_modules and .git
  ignored: ["node_modules/**", ".git/**"]
}, (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }
  
  console.log(stats.toString({
    colors: true,
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false
  }));
});

// Stop watching
process.on("SIGINT", () => {
  watching.close((err) => {
    if (err) console.error(err);
    console.log("Watching stopped");
  });
});

Stats Options

Build statistics and output formatting configuration.

interface StatsOptions {
  /** Preset configurations */
  preset?: 
    | "normal" 
    | "none" 
    | "minimal" 
    | "errors-only" 
    | "errors-warnings" 
    | "summary" 
    | "detailed" 
    | "verbose";
    
  /** All stats options (overrides preset) */
  all?: boolean;
  
  /** Show asset information */
  assets?: boolean;
  
  /** Sort assets */
  assetsSort?: string;
  
  /** Asset space limit */
  assetsSpace?: number;
  
  /** Show built date/time */
  builtAt?: boolean;
  
  /** Show chunks information */
  chunks?: boolean;
  
  /** Show chunk groups */
  chunkGroups?: boolean;
  
  /** Show chunk modules */
  chunkModules?: boolean;
  
  /** Chunk modules space limit */
  chunkModulesSpace?: number;
  
  /** Show chunk origins */
  chunkOrigins?: boolean;
  
  /** Sort chunks */
  chunksSort?: string;
  
  /** Show colors in output */
  colors?: boolean;
  
  /** Context directory for relative paths */
  context?: string;
  
  /** Show compilation date */
  date?: boolean;
  
  /** Show dependency count */
  dependenciesSpace?: number;
  
  /** Show build duration */
  timings?: boolean;
  
  /** Show entry points */
  entrypoints?: boolean | "auto";
  
  /** Show environment */
  env?: boolean;
  
  /** Show error details */
  errorDetails?: boolean | "auto";
  
  /** Show error stack traces */
  errorStack?: boolean;
  
  /** Show errors */
  errors?: boolean;
  
  /** Show errors count */
  errorsCount?: boolean;
  
  /** Show webpack hash */
  hash?: boolean;
  
  /** Show logging output */
  logging?: boolean | LoggingLevel;
  
  /** Show modules information */
  modules?: boolean;
  
  /** Sort modules */
  modulesSort?: string;
  
  /** Modules space limit */
  modulesSpace?: number;
  
  /** Show module trace for errors/warnings */
  moduleTrace?: boolean;
  
  /** Show output path */
  outputPath?: boolean;
  
  /** Show performance hints */
  performance?: boolean;
  
  /** Show preset used */
  preset?: string;
  
  /** Show provided exports */
  providedExports?: boolean;
  
  /** Show public path */
  publicPath?: boolean;
  
  /** Show reasons for module inclusion */
  reasons?: boolean;
  
  /** Reasons space limit */
  reasonsSpace?: number;
  
  /** Show related assets */
  relatedAssets?: boolean;
  
  /** Show runtime modules */
  runtimeModules?: boolean;
  
  /** Show source maps */
  source?: boolean;
  
  /** Show used exports */
  usedExports?: boolean;
  
  /** Show version */
  version?: boolean;
  
  /** Show warnings */
  warnings?: boolean;
  
  /** Show warnings count */
  warningsCount?: boolean;
  
  /** Warnings filter */
  warningsFilter?: string | RegExp | ((warning: string) => boolean) | Array<string | RegExp | ((warning: string) => boolean)>;
  
  /** Show children statistics */
  children?: boolean | StatsOptions;
}

type LoggingLevel = "none" | "error" | "warn" | "info" | "log" | "verbose";

Usage Examples:

module.exports = {
  // Preset-based configuration
  stats: "errors-only",
  
  // Detailed custom configuration
  stats: {
    colors: true,
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false,
    entrypoints: false,
    assets: false,
    version: false,
    builtAt: false,
    timings: true,
    performance: true,
    errors: true,
    warnings: true
  },
  
  // Development-friendly stats
  stats: {
    preset: "minimal",
    colors: true,
    timings: true,
    errors: true,
    warnings: true,
    errorDetails: true
  }
};

// Programmatic stats formatting
webpack(config, (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }
  
  console.log(stats.toString({
    chunks: false,
    colors: true,
    modules: false
  }));
  
  // JSON stats for analysis tools
  const statsJson = stats.toJson({
    assets: true,
    chunks: true,
    modules: true,
    errors: true,
    warnings: true
  });
});

Multi-Configuration Support

Webpack supports building multiple configurations simultaneously for different targets or environments.

/** Multiple configuration array */
type MultiConfiguration = Configuration[];

/** Function returning multiple configurations */
type MultiConfigurationFunction = (
  env: any,
  argv: any
) => MultiConfiguration | Promise<MultiConfiguration>;

Usage Examples:

// Array of configurations
module.exports = [
  // Client build
  {
    name: "client",
    entry: "./src/client/index.js",
    target: "web",
    output: {
      filename: "client.js",
      path: path.resolve(__dirname, "dist/client")
    }
  },
  
  // Server build  
  {
    name: "server",
    entry: "./src/server/index.js",
    target: "node",
    output: {
      filename: "server.js",
      path: path.resolve(__dirname, "dist/server")
    }
  },
  
  // Web Worker build
  {
    name: "worker",
    entry: "./src/worker/index.js",
    target: "webworker",
    output: {
      filename: "worker.js",
      path: path.resolve(__dirname, "dist")
    }
  }
];

// Function-based multi-configuration
module.exports = (env, argv) => {
  const isProduction = argv.mode === "production";
  
  return [
    {
      name: "main",
      entry: "./src/index.js",
      mode: argv.mode,
      optimization: {
        minimize: isProduction
      }
    },
    
    // Only build worker in production
    ...(isProduction ? [{
      name: "worker", 
      entry: "./src/worker.js",
      target: "webworker"
    }] : [])
  ];
};

// Shared configuration with environment-specific overrides
const baseConfig = {
  module: {
    rules: [
      { test: /\.js$/, use: "babel-loader" }
    ]
  }
};

module.exports = [
  {
    ...baseConfig,
    name: "development",
    mode: "development",
    devtool: "eval-source-map"
  },
  {
    ...baseConfig,
    name: "production", 
    mode: "production",
    devtool: "source-map"
  }
];

Common Configuration Patterns

Development Configuration

module.exports = {
  mode: "development",
  devtool: "eval-cheap-module-source-map",
  
  entry: {
    main: ["webpack-hot-middleware/client", "./src/index.js"]
  },
  
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    publicPath: "/"
  },
  
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            cacheDirectory: true
          }
        }
      }
    ]
  },
  
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("development")
    })
  ],
  
  optimization: {
    splitChunks: {
      chunks: "all"
    }
  },
  
  stats: "minimal",
  
  watchOptions: {
    aggregateTimeout: 300,
    ignored: /node_modules/
  }
};

Production Configuration

module.exports = {
  mode: "production",
  devtool: "source-map",
  
  entry: "./src/index.js",
  
  output: {
    filename: "[name].[contenthash].js",
    chunkFilename: "[name].[contenthash].chunk.js",
    path: path.resolve(__dirname, "dist"),
    publicPath: "/assets/",
    clean: true
  },
  
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: "babel-loader"
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"]
      }
    ]
  },
  
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash].css"
    }),
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("production")
    })
  ],
  
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true
          }
        }
      })
    ],
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all"
        }
      }
    },
    runtimeChunk: "single",
    moduleIds: "deterministic",
    chunkIds: "deterministic"
  },
  
  performance: {
    maxAssetSize: 250000,
    maxEntrypointSize: 250000
  }
};

Library Configuration

module.exports = {
  mode: "production",
  
  entry: "./src/index.js",
  
  output: {
    filename: "my-library.js",
    path: path.resolve(__dirname, "dist"),
    library: {
      name: "MyLibrary",
      type: "umd"
    },
    globalObject: "this"
  },
  
  externals: {
    react: {
      commonjs: "react",
      commonjs2: "react", 
      amd: "React",
      root: "React"
    }
  },
  
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: "babel-loader"
      }
    ]
  },
  
  optimization: {
    minimize: true
  }
};

Install with Tessl CLI

npx tessl i tessl/npm-webpack

docs

configuration.md

core-compilation.md

development-tools.md

index.md

module-system.md

optimization.md

plugins.md

runtime-system.md

utilities.md

tile.json