CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webpack-cli

CLI for webpack and friends - provides comprehensive command-line interface for webpack with configuration, building, serving, and analysis capabilities.

Pending
Overview
Eval results
Files

programmatic-api.mddocs/

Programmatic API

The WebpackCLI class provides complete programmatic access to webpack CLI functionality, allowing integration of webpack operations into custom Node.js applications and tooling.

Capabilities

WebpackCLI Class

Main class implementing the IWebpackCLI interface for programmatic webpack operations.

class WebpackCLI implements IWebpackCLI {
  // Properties
  colors: WebpackCLIColors;
  logger: WebpackCLILogger;
  isColorSupportChanged: boolean | undefined;
  webpack: typeof webpack;
  builtInOptionsCache: WebpackCLIBuiltInOption[] | undefined;
  program: WebpackCLICommand;

  // Constructor
  constructor();
}

Usage Example:

import CLI from "webpack-cli";

const cli = CLI;
await cli.run(["--mode", "production"]);

Core Execution Methods

Primary methods for running webpack operations programmatically.

/**
 * Main execution method - runs CLI with provided arguments
 * @param args - Command line arguments array
 * @param parseOptions - Optional parsing configuration
 */
run(args: string[], parseOptions?: ParseOptions): Promise<void>;

/**
 * Run webpack compilation with options
 * @param options - Webpack run options
 * @param isWatchCommand - Whether this is a watch command
 */
runWebpack(options: WebpackRunOptions, isWatchCommand: boolean): Promise<void>;

Usage Examples:

// Basic build
await cli.run(["./src/index.js", "--mode", "production"]);

// With custom options
await cli.run(["--config", "webpack.prod.js"], {
  from: "user"
});

// Direct webpack execution
await cli.runWebpack({
  config: webpackConfig,
  stats: true
}, false);

Configuration Management

Methods for loading, validating, and building webpack configurations.

/**
 * Load webpack configuration from files
 * @param options - Configuration loading options
 * @returns Promise resolving to WebpackCLIConfig
 */
loadConfig(options: Partial<WebpackDevServerOptions>): Promise<WebpackCLIConfig>;

/**
 * Build and process configuration with CLI options
 * @param config - Base configuration
 * @param options - CLI options to merge
 * @returns Promise resolving to processed config
 */
buildConfig(config: WebpackCLIConfig, options: WebpackDevServerOptions): Promise<WebpackCLIConfig>;

Usage Examples:

// Load configuration
const config = await cli.loadConfig({
  config: ["webpack.config.js"],
  mode: "production"
});

// Build configuration with options
const builtConfig = await cli.buildConfig(config, {
  mode: "production",
  watch: false,
  entry: "./src/index.js"
});

Webpack Integration

Methods for webpack loading and compiler creation.

/**
 * Load webpack module dynamically
 * @param handleError - Whether to handle loading errors
 * @returns Promise resolving to webpack module
 */
loadWebpack(handleError?: boolean): Promise<typeof webpack>;

/**
 * Create webpack compiler instance
 * @param options - Compiler creation options
 * @param callback - Optional compilation callback
 * @returns Promise resolving to Compiler or MultiCompiler
 */
createCompiler(
  options: Partial<WebpackDevServerOptions>,
  callback?: Callback<[Error | undefined, Stats | MultiStats | undefined]>
): Promise<WebpackCompiler>;

Usage Examples:

// Load webpack
const webpack = await cli.loadWebpack();

// Create compiler
const compiler = await cli.createCompiler({
  config: ["webpack.config.js"],
  mode: "development"
});

// Create compiler with callback
const compiler = await cli.createCompiler({
  config: ["webpack.config.js"]
}, (err, stats) => {
  if (err) console.error(err);
  console.log(stats?.toString());
});

Package Management

Methods for package installation and management.

/**
 * Check if a package exists in node_modules
 * @param packageName - Name of package to check
 * @returns Boolean indicating if package exists
 */
checkPackageExists(packageName: string): boolean;

/**
 * Get available package managers on the system
 * @returns Array of available package managers
 */
getAvailablePackageManagers(): PackageManager[];

/**
 * Get the default package manager
 * @returns Default package manager or undefined
 */
getDefaultPackageManager(): PackageManager | undefined;

/**
 * Install a package using available package manager
 * @param packageName - Package to install
 * @param options - Installation options
 * @returns Promise resolving to installation output
 */
doInstall(packageName: string, options?: PackageInstallOptions): Promise<string>;

Usage Examples:

// Check package
const hasWebpack = cli.checkPackageExists("webpack");

// Get package managers
const managers = cli.getAvailablePackageManagers();
const defaultPM = cli.getDefaultPackageManager();

// Install package
await cli.doInstall("webpack-dev-server", {
  packageManager: "npm"
});

File and Module Operations

Utilities for loading JSON files and modules.

/**
 * Load JSON file synchronously
 * @param path - Path to JSON file
 * @param handleError - Whether to handle loading errors
 * @returns Parsed JSON object
 */
loadJSONFile<T = unknown>(path: string, handleError: boolean): T;

/**
 * Try to load a module using require then import
 * @param module - Module name to load
 * @param handleError - Whether to handle loading errors
 * @param moduleType - Type of module loading to attempt
 * @returns Promise resolving to loaded module
 */
tryRequireThenImport<T = unknown>(
  module: string, 
  handleError: boolean,
  moduleType?: "unknown" | "commonjs" | "esm"
): Promise<T>;

Usage Examples:

// Load JSON configuration (synchronous)
const packageJson = cli.loadJSONFile<PackageJSON>("./package.json", true);

// Load module with module type
const plugin = await cli.tryRequireThenImport("webpack-bundle-analyzer", false, "unknown");

// Load ESM module specifically
const esmModule = await cli.tryRequireThenImport("./config.mjs", false, "esm");

Command and Option Management

Methods for creating commands and managing CLI options.

/**
 * Create a CLI command
 * @param commandOptions - Command configuration
 * @param options - CLI command options
 * @param action - Command action function
 * @returns Promise resolving to WebpackCLICommand or undefined
 */
makeCommand(
  commandOptions: WebpackCLIOptions,
  options: WebpackCLICommandOptions,
  action: CommandAction
): Promise<WebpackCLICommand | undefined>;

/**
 * Add option to a command
 * @param command - Target command
 * @param option - Option to add
 */
makeOption(command: WebpackCLICommand, option: WebpackCLIBuiltInOption): void;

/**
 * Get all built-in CLI options
 * @returns Array of built-in options
 */
getBuiltInOptions(): WebpackCLIBuiltInOption[];

Info Command Integration

Methods for system information output.

/**
 * Get info command options
 * @returns Array of info command options
 */
getInfoOptions(): WebpackCLIBuiltInOption[];

/**
 * Get formatted info output
 * @param options - Info output options
 * @returns Promise resolving to formatted info string
 */
getInfoOutput(options: { 
  output: string; 
  additionalPackage: string[] 
}): Promise<string>;

Usage Examples:

// Get system info
const infoOutput = await cli.getInfoOutput({
  output: "json",
  additionalPackage: ["react", "webpack-dev-server"]
});

console.log(infoOutput);

Utility Methods

Helper methods for string formatting and type checking.

/**
 * Type guard to check if compiler is a MultiCompiler
 * @param compiler - Webpack compiler instance
 * @returns True if compiler is MultiCompiler
 */
isMultipleCompiler(compiler: WebpackCompiler): compiler is MultiCompiler;

/**
 * Type guard to check if value is a Promise
 * @param value - Value to check
 * @returns True if value is a Promise
 */
isPromise<T>(value: Promise<T>): value is Promise<T>;

/**
 * Type guard to check if value is a function
 * @param value - Value to check
 * @returns True if value is a function
 */
isFunction(value: unknown): value is CallableFunction;

/**
 * Type guard to check if error is a webpack validation error
 * @param error - Error to check
 * @returns True if error is WebpackError
 */
isValidationError(error: Error): error is WebpackError;

/**
 * Convert string to kebab-case
 * @param str - String to convert
 * @returns Kebab-case string
 */
toKebabCase(str: string): string;

/**
 * Capitalize first letter of string
 * @param str - String to capitalize
 * @returns String with first letter capitalized
 */
capitalizeFirstLetter(str: string): string;

/**
 * Get CLI logger instance
 * @returns WebpackCLI logger
 */
getLogger(): WebpackCLILogger;

/**
 * Create colors utility with optional color support override
 * @param useColors - Force color support on/off
 * @returns Colors utility instance
 */
createColors(useColors?: boolean): WebpackCLIColors;

/**
 * Check if compiler needs stdin watching
 * @param compiler - Webpack compiler instance
 * @returns True if stdin watching is needed
 */
needWatchStdin(compiler: Compiler | MultiCompiler): boolean;

Types

interface WebpackCLIConfig {
  options: WebpackConfiguration | WebpackConfiguration[];
  path: WeakMap<object, string[]>;
}

interface WebpackRunOptions extends WebpackOptionsNormalized {
  progress?: boolean | "profile";
  json?: boolean;
  argv?: Argv;
  env: Env;
  failOnWarnings?: boolean;
  isWatchingLikeCommand?: boolean;
}

interface WebpackDevServerOptions extends DevServerConfig, WebpackConfiguration, ClientConfiguration, AssetEmittedInfo, WebpackOptionsNormalized, FileCacheOptions, Argv {
  nodeEnv?: string;
  watchOptionsStdin?: boolean;
  progress?: boolean | "profile" | undefined;
  analyze?: boolean;
  prefetch?: string;
  json?: boolean;
  entry: EntryOptions;
  merge?: boolean;
  config: string[];
  configName?: string[];
  disableInterpret?: boolean;
  extends?: string[];
  argv: Argv;
}

interface PackageInstallOptions {
  preMessage?: () => void;
}

interface WebpackCLIBuiltInOption extends WebpackCLIBuiltInFlag {
  hidden?: boolean;
  group?: "core";
}

interface WebpackCLIBuiltInFlag {
  name: string;
  alias?: string;
  type?: (
    value: string,
    previous: Record<string, BasicPrimitive | object>,
  ) => Record<string, BasicPrimitive | object>;
  configs?: Partial<FlagConfig>[];
  negative?: boolean;
  multiple?: boolean;
  valueName?: string;
  description?: string;
  describe?: string;
  negatedDescription?: string;
  defaultValue?: string;
  helpLevel: "minimum" | "verbose";
}

type PackageManager = "pnpm" | "yarn" | "npm";
type WebpackCompiler = Compiler | MultiCompiler;
type StringFormatter = (str: string) => string;
type CommandAction = (...args: any[]) => Promise<void> | void;
type BasicPrimitive = string | boolean | number;
type Callback<T extends unknown[]> = (...args: T) => void;

interface FlagConfig {
  negatedDescription: string;
  type: FlagType;
  values: FlagType[];
}

type FlagType = boolean | "enum" | "string" | "path" | "number" | "boolean" | "RegExp" | "reset";

interface Env {
  WEBPACK_BUNDLE?: boolean;
  WEBPACK_BUILD?: boolean;
  WEBPACK_WATCH?: boolean;
  WEBPACK_SERVE?: boolean;
  WEBPACK_PACKAGE?: string;
  WEBPACK_DEV_SERVER_PACKAGE?: string;
}

interface Argv extends Record<string, any> {
  env?: Env;
}

Install with Tessl CLI

npx tessl i tessl/npm-webpack-cli

docs

cli-interface.md

index.md

plugin-system.md

programmatic-api.md

tile.json