CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-microbundle

Zero-configuration bundler for tiny JavaScript libraries, powered by Rollup.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

programmatic-api.mddocs/

Programmatic API

The microbundle programmatic API provides complete control over the bundling process for integration into build scripts, development tools, or other Node.js applications.

Capabilities

Main Bundler Function

Core bundling function that processes JavaScript modules and generates multiple output formats.

/**
 * Bundle JavaScript modules with zero configuration
 * @param inputOptions - Configuration options for bundling
 * @returns Promise resolving to build results with output message and optional watchers
 */
function microbundle(inputOptions: MicrobundleOptions): Promise<MicrobundleResult>;

Usage Examples:

import microbundle from "microbundle";

// Basic build
const result = await microbundle({
  entries: ["src/index.js"],
  format: "esm,cjs",
  output: "dist"
});
console.log(result.output);

// Development build with watch mode
const watchResult = await microbundle({
  entries: ["src/index.js", "src/cli.js"],
  format: "modern,esm,cjs,umd",
  watch: true,
  sourcemap: true,
  onBuild: (event) => console.log("Build completed!"),
  onError: (event) => console.error("Build failed:", event.error)
});

// Node.js library build
const nodeResult = await microbundle({
  entries: ["src/server.js"],
  format: "cjs",
  target: "node",
  compress: false,
  external: "none"
});

Input Options

Configuration object passed to the main microbundle function.

interface MicrobundleOptions {
  /** Entry module paths to bundle (default: auto-detected from package.json) */
  entries?: string[];
  
  /** Output formats as comma-separated string (default: "modern,esm,cjs,umd") */
  format?: string;
  
  /** Alternative property name for format */
  formats?: string;
  
  /** Output directory or file path (default: from package.json main/module fields) */
  output?: string;
  
  /** Enable watch mode for development (default: false) */
  watch?: boolean;
  
  /** Target environment: 'web' for browsers, 'node' for Node.js (default: 'web') */
  target?: "web" | "node";
  
  /** Enable/disable Terser compression (default: true for web, false for node) */
  compress?: boolean;
  
  /** Generate source maps: true, false, or 'inline' (default: true) */
  sourcemap?: boolean | string;
  
  /** Working directory (default: process.cwd()) */
  cwd?: string;
  
  /** External dependencies: 'none' or comma-separated module names */
  external?: string;
  
  /** Global variable mappings for UMD builds (e.g., 'react=React,jquery=$') */
  globals?: string;
  
  /** Build-time constant definitions (e.g., 'API_URL=https://api.example.com') */
  define?: string;
  
  /** Module import aliases (e.g., 'react=preact/compat') */
  alias?: string;
  
  /** Enforce undefined global context and add "use strict" */
  strict?: boolean;
  
  /** UMD global name (default: camelCase of package name) */
  name?: string;
  
  /** Show raw byte sizes instead of gzipped (default: false) */
  raw?: boolean;
  
  /** JSX pragma function (default: 'h') */
  jsx?: string;
  
  /** JSX fragment pragma (default: 'Fragment') */
  jsxFragment?: string;
  
  /** JSX import source for automatic JSX runtime */
  jsxImportSource?: string;
  
  /** Path to custom TypeScript configuration file */
  tsconfig?: string;
  
  /** Generate TypeScript declaration files (default: from package.json types field) */
  generateTypes?: boolean;
  
  /** CSS output mode: 'inline' or 'external' (default: 'external') */
  css?: string;
  
  /** CSS modules configuration string */
  "css-modules"?: string;
  
  /** Bundle web workers using off-main-thread plugin (default: false) */
  workers?: boolean;
  
  /** Generate bundle composition visualization (default: false) */
  visualize?: boolean;
  
  /** Output files using package.json main entries pattern (default: true) */
  "pkg-main"?: boolean;
  
  /** Watch mode start callback */
  onStart?: (event: WatchEvent) => void;
  
  /** Watch mode build completion callback */
  onBuild?: (event: WatchEvent) => void;
  
  /** Watch mode error callback */
  onError?: (event: WatchEvent) => void;
}

Build Result

Object returned by the microbundle function containing build information.

interface MicrobundleResult {
  /** Human-readable build output message with file sizes and paths */
  output: string;
  
  /** File watchers for watch mode (only present when watch: true) */
  watchers?: Record<string, any>;
}

Watch Events

Event objects passed to watch mode callbacks.

interface WatchEvent {
  /** Event code: 'START', 'BUNDLE_START', 'BUNDLE_END', 'END', 'ERROR' */
  code: string;
  
  /** Error object (only present for ERROR events) */
  error?: Error;
  
  /** Input file path (for BUNDLE_START and BUNDLE_END events) */
  input?: string;
  
  /** Output bundle information */
  result?: any;
}

Advanced Usage Examples:

import microbundle from "microbundle";

// Custom build pipeline
async function buildLibrary(inputPath, outputPath) {
  return await microbundle({
    entries: [inputPath],
    output: outputPath,
    format: "modern,esm,cjs",
    compress: process.env.NODE_ENV === "production",
    sourcemap: process.env.NODE_ENV !== "production",
    onStart: () => console.log("Starting build..."),
    onBuild: () => console.log("Build completed successfully"),
    onError: (event) => {
      console.error("Build failed:", event.error.message);
      process.exit(1);
    }
  });
}

// Development server integration
async function startDevMode() {
  const result = await microbundle({
    entries: ["src/index.ts"],
    format: "esm",
    watch: true,
    sourcemap: "inline",
    compress: false,
    onBuild: (event) => {
      // Trigger browser reload or other dev server actions
      notifyDevServer();
    }
  });
  
  return result.watchers;
}

Error Handling

The microbundle function can throw various types of errors:

try {
  const result = await microbundle(options);
  console.log(result.output);
} catch (error) {
  if (error.code === 'UNRESOLVED_IMPORT') {
    console.error('Missing dependency:', error.message);
  } else if (error.plugin) {
    console.error(`${error.plugin} plugin error:`, error.message);
  } else {
    console.error('Build error:', error.message);
  }
}

TypeScript Integration

Microbundle provides excellent TypeScript support with automatic type generation:

// Build TypeScript library with declarations
const result = await microbundle({
  entries: ["src/index.ts"],
  format: "esm,cjs",
  generateTypes: true,
  tsconfig: "tsconfig.build.json"
});

// Mixed JavaScript and TypeScript
const mixedResult = await microbundle({
  entries: ["src/index.js", "src/types.ts"],
  generateTypes: true  // Will generate .d.ts files
});

Configuration Merging

Microbundle automatically merges configuration from multiple sources in this order of precedence:

  1. Command-line arguments (highest priority)
  2. Direct function options
  3. publishConfig from package.json
  4. Standard package.json fields (lowest priority)
// Example: publishConfig override
// package.json:
{
  "main": "src/index.js",        // Used in development
  "publishConfig": {
    "main": "dist/index.js"      // Used by microbundle
  }
}

docs

cli-interface.md

index.md

programmatic-api.md

tile.json