Skip to Content
vitus·labs
Tools Rolldown

Tools Rolldown

Rolldown-based build tool for library packages — ESM/CJS/UMD output with DTS generation and platform globals.

@vitus-labs/tools-rolldown is the primary build tool for the vitus-labs ecosystem. It uses Rolldown (a Rust-based bundler) to produce optimized library bundles with automatic TypeScript declaration generation.

Installation

npm install @vitus-labs/tools-rolldown

Quick Start

Add a build script to your package.json:

{
  "scripts": {
    "build": "vl_rolldown_build"
  }
}

Run it:

bun run build

The tool reads your package.json fields (exports, main, module, …) and writes each output to the path those fields declare.

Requirements

  • Node.js >= 22 (declared in engines).
  • No peer dependencies — rolldown, rolldown-plugin-dts and @vitus-labs/tools-core are regular dependencies.
  • Works with TypeScript 6 and TypeScript 7: rolldown-plugin-dts switches to its tsgo generator automatically under TypeScript 7. With typescript: true (default) a tsconfig.json is expected in the package root.

How It Works

  1. Loads config from vl-tools.config.mjs (via tools-core)
  2. Cleans outputDir
  3. Generates a build pipeline from package.json (exports/main/module/react-native/browser/umd:main/unpkg) — or from entries when configured
  4. Bundles each variant with Rolldown, injecting platform globals (__WEB__, __NATIVE__, etc.)
  5. Copies copyFiles assets
  6. Generates .d.ts files with rolldown-plugin-dts

Every JS build emits source maps (configurable), a file size report and a bundle visualization.

CLI Commands

vl_rolldown_build

Production build — generates all output formats defined in package.json.

vl_rolldown_build

vl_rolldown_build-watch

Watch mode — rebuilds the JS bundles on file changes (development). Uses the same build pipeline and config as vl_rolldown_build; declarations are not regenerated in watch mode and copyFiles is not run. Stop with Ctrl+C.

vl_rolldown_build-watch
{
  "scripts": {
    "build": "vl_rolldown_build",
    "dev": "vl_rolldown_build-watch"
  }
}

Configuration

Configure via vl-tools.config.mjs under the build key:

// vl-tools.config.mjs
export default {
  build: {
    sourceDir: 'src',           // Source directory; entry is <sourceDir>/index.* (default: 'src')
    outputDir: 'lib',           // Directory cleaned before each build (default: 'lib')
    replaceGlobals: true,       // Inject platform globals (default: true)
    typescript: true,           // Generate .d.ts files (default: true)
    filesize: true,             // Show file sizes in console (default: true)
    sourcemap: true,            // true | false | 'hidden' | 'inline' (default: true)
    visualise: {                // Bundle visualization, or `false` to disable
      template: 'network',      // any rollup-plugin-visualizer template, e.g. 'treemap'
      gzipSize: true,
      outputDir: 'analysis',
    },
    extensions: ['.json', '.js', '.jsx', '.ts', '.tsx', '.es6', '.es', '.mjs'],
    external: ['react/jsx-runtime'],  // Extra externals (replaces the default list)
    globals: {                  // UMD/IIFE globals as { GlobalName: 'module-id' }
      React: 'react',
    },
  },
}

Config files cascade: every vl-tools.config.mjs from the current directory upward is loaded and deep-merged (root first, the closest file wins). Objects merge key by key; arrays (e.g. external, extensions) replace the default wholesale.

The exclude, include, typesDir and esModulesOnly options were removed from tools-rolldown in 2.8.0 — they were documented but never read. Declarations are written to the path in package.json (types), not to a configurable directory.

Output Format Detection

The tool reads your package.json to determine what to build:

exports Field (Preferred)

{
  "exports": {
    ".": {
      "import": "./lib/index.js",
      "require": "./lib/index.cjs",
      "types": "./lib/index.d.ts"
    }
  }
}
ConditionFormatPlatform
importESMuniversal
requireCJSuniversal
nodeESMnode
defaultESMuniversal (only when there is no import)

Nested condition objects such as "import": { "types": "...", "default": "..." } are flattened (default, then import, then require). A plain string exports builds a single ESM output.

The exports field is only read when the package has "type": "module". In a CommonJS package, use main/module instead.

Subpath Exports

Packages with multiple entry points are automatically detected and built:

{
  "exports": {
    ".": {
      "import": "./lib/index.js",
      "types": "./lib/types/index.d.ts"
    },
    "./devtools": {
      "import": "./lib/devtools.js",
      "types": "./lib/types/devtools.d.ts"
    },
    "./validation/zod": {
      "import": "./lib/validation/zod.js",
      "types": "./lib/types/validation/zod.d.ts"
    }
  }
}

Each subpath is resolved to a source file by convention (<sourceDir> is src by default):

  • "." → src/index (.ts, .tsx, .js or .jsx)
  • "./devtools" → src/devtools (resolves to src/devtools.ts or src/devtools/index.ts)
  • "./validation/zod" → src/validation/zod

Separate .d.ts declarations are generated for each subpath with a types field (top-level or nested inside import).

Subpaths that share format, env, platform and output extension are built in a single Rolldown invocation, so code shared between entries is emitted once into _chunks/ (with the .js/.mjs/.cjs extension from package.json).

  • Passthrough string exports like "./package.json": "./package.json" are skipped (only string targets ending in .js/.mjs are built).
  • Wildcard subpaths ("./features/*") are skipped with a warning — list the subpaths explicitly.
  • A file referenced by several fields (e.g. exports.import and module) is built only once.

main / module Fields (Fallback)

{
  "main": "lib/index.cjs",
  "module": "lib/index.js"
}
  • main → CJS (or ESM if type: "module")
  • module → ESM
  • react-native → ESM with native platform (only when it differs from module)
  • umd:main → UMD
  • unpkg → UMD, production (minified)

Browser Field

When the object form of browser maps a built file to a different file, a separate browser build is generated (and the original variant is built for the node platform):

{
  "main": "lib/index.js",
  "browser": {
    "./lib/index.js": "./lib/browser.js"
  }
}

Only "./…": "./…" string mappings produce builds; the string form of browser and false values (e.g. { "fs": false }) are ignored.

Platform Globals

When replaceGlobals: true (default), these constants are injected at build time:

GlobalTypeDescription
__VERSION__stringPackage version from package.json
__WEB__booleantrue for web/node/browser platforms
__NATIVE__booleantrue for React Native
__BROWSER__booleantrue for browser-only
__NODE__booleantrue for Node.js
__CLIENT__booleantrue for browser + native

Platform assignment depends on the build variant:

Platform__WEB____NATIVE____BROWSER____NODE____CLIENT__
universaltruefalsefalsefalsefalse
browsertruefalsetruefalsetrue
nodetruefalsefalsetruefalse
nativefalsetruefalsefalsetrue

Production builds (env: 'production', e.g. unpkg) are minified and additionally replace process.env.NODE_ENV with "production".

Add the type declarations for these constants to your tsconfig.json:

{
  "compilerOptions": {
    "types": ["@vitus-labs/tools-rolldown/global"]
  }
}

The shipped global types declare __BROWSER__, __WEB__, __NATIVE__, __NODE__ and __CLIENT__ (not __VERSION__).

Type Generation

When typescript: true, declarations are generated with rolldown-plugin-dts in a separate step after the JS builds. The output path is read from package.json (exports.types, types or typings):

{
  "exports": {
    ".": {
      "types": "./lib/index.d.ts"
    }
  }
}

For packages with subpath exports, a separate .d.ts file is generated for each subpath that has a types field. Declarations that share an output directory are generated in a single pass; types shared between entries go to _dts_chunks/ (kept apart from the JS _chunks/, so types and JS can share a directory).

External Dependencies

All dependencies, peerDependencies and optionalDependencies from package.json are automatically marked as external (not bundled), including their deep imports (echarts also matches echarts/core). node:* built-ins are always external. Additional externals can be added via config (strings get the same deep-import matching; RegExps are used as-is):

export default {
  build: {
    external: ['react/jsx-runtime', 'some-other-package'],
  },
}

Setting external replaces the default ['react/jsx-runtime'], so include it again if you need it. bundleAll: true disables externals entirely.

Bundle Visualization

Enabled by default. Each JS build writes an interactive HTML report from rollup-plugin-visualizer next to its output, in visualise.outputDir:

lib/analysis/index.js.html

template defaults to 'network' and accepts any rollup-plugin-visualizer template (e.g. 'treemap', 'sunburst'). Set visualise: false to turn it off.

Sourcemaps

JS-bundle sourcemap generation mirrors rolldown's native output.sourcemap API:

sourcemapEmitssourceMappingURL commentUse when
true (default)separate .js.map fileyesOSS libraries — full debuggability
'hidden'separate .js.map filenoClosed-source: ship maps to error-reporting service (Sentry, etc.) without leaking via the bundle
'inline'base64 map embedded in .jsn/aVery small bundles, simpler deploy
falsenothingn/aYou explicitly don't want maps
// vl-tools.config.mjs — privacy without losing debuggability
export default {
  build: {
    sourcemap: 'hidden',
  },
}

DTS output never includes sourcemaps (declarations don't need them).

Advanced Build Options

For non-library builds such as Chrome extensions, CLI tools, serverless functions, or Electron apps, you can bypass the package.json-driven pipeline with explicit configuration:

// vl-tools.config.mjs
export default {
  build: {
    // Explicit entries — skips package.json field detection
    entries: [
      { input: 'src/background.ts', file: 'dist/background.js', format: 'iife', env: 'production' },
      { input: 'src/content.ts', file: 'dist/content.js', format: 'iife' },
      { input: 'src/popup.ts', file: 'dist/popup.js', format: 'es' },
    ],

    // Bundle all dependencies (no externals)
    bundleAll: true,

    // Copy static assets after build
    copyFiles: [
      { from: 'src/manifest.json', to: 'dist/manifest.json' },
      { from: 'src/popup.html', to: 'dist/popup.html' },
    ],

    // Inject text at top/bottom of output
    banner: '#!/usr/bin/env node',
    footer: '// Built with @vitus-labs/tools-rolldown',

    // Resolve aliases
    alias: {
      '@': './src',
    },

    // Custom rolldown plugins (appended to built-in ones)
    plugins: [],

    // Disable declarations for non-library builds
    typescript: false,
  },
}
OptionTypeDefaultDescription
entriesArray<{ input, file, format?, env?, platform? }>undefinedExplicit entry points (bypasses package.json detection)
bundleAllbooleanfalseBundle all dependencies instead of externalizing
copyFilesArray<{ from, to }>undefinedCopy static files/directories after build
bannerstringundefinedText injected at the top of each output file
footerstringundefinedText injected at the bottom of each output file
aliasRecord<string, string>undefinedResolve aliases for import remapping
pluginsRolldownPlugin[][]Custom plugins appended to built-in ones

Entry Format Options

Each entry in the entries array supports:

FieldRequiredDefaultValues
inputyes—Source file path (e.g., 'src/index.ts')
fileyes—Output file path (e.g., 'dist/index.js')
formatno'es''es', 'cjs', 'umd', 'iife'
envno'development''development', 'production'
platformno'universal''universal', 'browser', 'node', 'native'

Use Cases

  • Chrome extensions — multiple IIFE entries, bundleAll: true, copyFiles for manifest/HTML
  • CLI tools — single entry, banner: '#!/usr/bin/env node', bundleAll: true
  • AWS Lambda — single entry, bundleAll: true, env: 'production'
  • Electron — separate entries for main (node) and renderer (browser)
  • Web Workers — IIFE or ES entry alongside the main app

Build Pipeline

Builds run sequentially. A typical library with ESM + CJS + types logs something like:

 rolldown  @scope/my-lib v1.0.0

Cleaning lib/
Building 2 bundles...

  + ESM -> lib/index.js (40ms)
  + CJS -> lib/index.cjs (35ms)

Generating declarations...
  + DTS -> ./lib/index.d.ts (600ms)

Done in 700ms

Each build:

  1. Resolves modules with platform-specific extensions first (e.g. .native.ts before .ts)
  2. Replaces platform globals
  3. Generates source maps
  4. Reports file sizes
  5. Produces a visualization report

Tree-shaking assumes modules have no side effects (moduleSideEffects: false).

Edit on GitHub

Last updated on

On this page