Next-generation ES module bundler that compiles small pieces of code into larger, more complex applications or libraries
—
Type-safe configuration utilities and loading mechanisms for managing complex build setups and development workflows. Rollup provides comprehensive configuration support including file loading, type helpers, and option merging.
Type helper function that provides IDE support and type checking for Rollup configuration files without affecting runtime behavior.
/**
* Type helper for IDE support in configuration files
* @param options - Rollup configuration options
* @returns The same options with type information preserved
*/
function defineConfig<T extends RollupOptions | RollupOptions[] | RollupOptionsFunction>(
options: T
): T;
type RollupOptionsFunction = (
commandLineArguments: Record<string, any>
) => MaybePromise<RollupOptions | RollupOptions[]>;Usage Examples:
import { defineConfig } from "rollup";
// Single configuration
export default defineConfig({
input: "src/main.js",
output: {
file: "dist/bundle.js",
format: "esm"
}
});
// Multiple configurations
export default defineConfig([
{
input: "src/main.js",
output: { file: "dist/esm.js", format: "esm" }
},
{
input: "src/main.js",
output: { file: "dist/cjs.js", format: "cjs" }
}
]);
// Function-based configuration
export default defineConfig((commandLineArgs) => {
const isProduction = commandLineArgs.watch !== true;
return {
input: "src/main.js",
output: {
file: "dist/bundle.js",
format: "esm",
sourcemap: !isProduction
},
plugins: isProduction ? [terser()] : []
};
});Utility for loading and processing Rollup configuration files programmatically, with support for various file formats and command-line option merging.
/**
* Loads and processes Rollup configuration files
* @param fileName - Path to configuration file
* @param commandOptions - Command-line options to merge
* @param watchMode - Whether running in watch mode
* @returns Promise resolving to processed configuration and warnings
*/
function loadConfigFile(
fileName: string,
commandOptions?: object,
watchMode?: boolean
): Promise<{
options: MergedRollupOptions[];
warnings: BatchWarnings;
}>;
interface MergedRollupOptions extends InputOptionsWithPlugins {
output: OutputOptions[];
}
interface BatchWarnings {
add: (warning: RollupLog) => void;
flush: () => void;
log: LoggingFunction;
}Usage Examples:
import { loadConfigFile } from "rollup/loadConfigFile";
// Load configuration file
const { options, warnings } = await loadConfigFile(
"./rollup.config.js",
{ format: "esm" }, // command options
false // not watch mode
);
// Process each configuration
for (const inputOptions of options) {
const bundle = await rollup(inputOptions);
for (const outputOptions of inputOptions.output) {
await bundle.write(outputOptions);
}
await bundle.close();
}
// Handle warnings
warnings.flush();Main configuration interface extending InputOptions with optional output configuration.
interface RollupOptions extends InputOptions {
/** Output configuration (can be array for multiple outputs) */
output?: OutputOptions | OutputOptions[];
}Comprehensive input configuration options for controlling bundle creation behavior.
interface InputOptions {
/** Entry point(s) for bundling */
input?: InputOption;
/** External dependencies to exclude */
external?: ExternalOption;
/** Input processing plugins */
plugins?: InputPluginOption;
/** Build caching configuration */
cache?: boolean | RollupCache;
/** Tree-shaking options */
treeshake?: boolean | TreeshakingPreset | TreeshakingOptions;
/** Watch mode configuration */
watch?: WatcherOptions | false;
/** Logging configuration */
logLevel?: LogLevelOption;
onLog?: LogHandlerWithDefault;
/** @deprecated Use onLog instead */
onwarn?: WarningHandlerWithDefault;
/** Module context configuration */
context?: string;
moduleContext?: ((id: string) => string | null) | Record<string, string>;
/** File system abstraction */
fs?: RollupFsModule;
/** Experimental features */
experimentalCacheExpiry?: number;
experimentalLogSideEffects?: boolean;
/** External handling options */
makeAbsoluteExternalsRelative?: boolean | 'ifRelativeSource';
/** Performance options */
maxParallelFileOps?: number;
perf?: boolean;
/** Entry signature handling */
preserveEntrySignatures?: PreserveEntrySignaturesOption;
/** Symlink handling */
preserveSymlinks?: boolean;
/** Missing export handling */
shimMissingExports?: boolean;
/** Deprecation warnings */
strictDeprecations?: boolean;
/** JSX processing */
jsx?: false | JsxPreset | JsxOptions;
}
type InputOption = string | string[] | Record<string, string>;
type LogLevelOption = LogLevel | 'silent';
type PreserveEntrySignaturesOption = false | 'strict' | 'allow-extension' | 'exports-only';Complete output configuration for controlling bundle generation and writing.
interface OutputOptions {
/** Output format */
format?: ModuleFormat;
/** Single file output */
file?: string;
/** Multiple file output directory */
dir?: string;
/** Output processing plugins */
plugins?: OutputPluginOption;
/** Source map configuration */
sourcemap?: boolean | 'inline' | 'hidden';
sourcemapBaseUrl?: string;
sourcemapExcludeSources?: boolean;
sourcemapFile?: string;
sourcemapFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
sourcemapIgnoreList?: boolean | SourcemapIgnoreListOption;
sourcemapPathTransform?: SourcemapPathTransformOption;
sourcemapDebugIds?: boolean;
/** File naming */
entryFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
chunkFileNames?: string | ((chunkInfo: PreRenderedChunk) => string);
assetFileNames?: string | ((chunkInfo: PreRenderedAsset) => string);
/** Code generation */
banner?: string | AddonFunction;
footer?: string | AddonFunction;
intro?: string | AddonFunction;
outro?: string | AddonFunction;
compact?: boolean;
generatedCode?: GeneratedCodePreset | GeneratedCodeOptions;
/** Module configuration */
exports?: 'default' | 'named' | 'none' | 'auto';
esModule?: boolean | 'if-default-prop';
externalLiveBindings?: boolean;
freeze?: boolean;
indent?: string | boolean;
inlineDynamicImports?: boolean;
interop?: InteropType | GetInterop;
minifyInternalExports?: boolean;
strict?: boolean;
/** Format-specific options */
name?: string; // UMD/IIFE global name
globals?: GlobalsOption;
extend?: boolean; // UMD extend existing global
noConflict?: boolean; // UMD noConflict mode
amd?: AmdOptions;
systemNullSetters?: boolean;
/** Chunking */
manualChunks?: ManualChunksOption;
experimentalMinChunkSize?: number;
/** Advanced options */
paths?: OptionsPaths;
preserveModules?: boolean;
preserveModulesRoot?: string;
hoistTransitiveImports?: boolean;
importAttributesKey?: ImportAttributesKey;
externalImportAttributes?: boolean;
/** @deprecated Use externalImportAttributes */
externalImportAssertions?: boolean;
reexportProtoFromExternal?: boolean;
sanitizeFileName?: boolean | ((fileName: string) => string);
validate?: boolean;
virtualDirname?: string;
dynamicImportInCjs?: boolean;
hashCharacters?: HashCharacters;
}
type ModuleFormat = 'amd' | 'cjs' | 'es' | 'iife' | 'system' | 'umd' | 'commonjs' | 'esm' | 'module' | 'systemjs';
type HashCharacters = 'base64' | 'base36' | 'hex';
type ImportAttributesKey = 'with' | 'assert';Advanced tree-shaking configuration for fine-tuning dead code elimination.
interface TreeshakingOptions extends Partial<Omit<NormalizedTreeshakingOptions, 'moduleSideEffects'>> {
/** Module side effects configuration */
moduleSideEffects?: ModuleSideEffectsOption;
/** Preset configuration */
preset?: TreeshakingPreset;
}
interface NormalizedTreeshakingOptions {
/** Respect /*#__PURE__*/ annotations */
annotations: boolean;
/** Variable declaration hoisting behavior */
correctVarValueBeforeDeclaration: boolean;
/** Manual pure function annotations */
manualPureFunctions: readonly string[];
/** Module side effects detection */
moduleSideEffects: HasModuleSideEffects;
/** Property access side effects */
propertyReadSideEffects: boolean | 'always';
/** Try-catch deoptimization */
tryCatchDeoptimization: boolean;
/** Unknown global side effects */
unknownGlobalSideEffects: boolean;
}
type ModuleSideEffectsOption = boolean | 'no-external' | string[] | HasModuleSideEffects;
type TreeshakingPreset = 'smallest' | 'safest' | 'recommended';
type HasModuleSideEffects = (id: string, external: boolean) => boolean;File watching configuration for development workflows.
interface WatcherOptions {
/** Allow input files inside output directory */
allowInputInsideOutputPath?: boolean;
/** Debounce delay for rebuilds */
buildDelay?: number;
/** Chokidar file watcher options */
chokidar?: ChokidarOptions;
/** Clear screen on rebuild */
clearScreen?: boolean;
/** Files to exclude from watching */
exclude?: string | RegExp | (string | RegExp)[];
/** Files to include in watching */
include?: string | RegExp | (string | RegExp)[];
/** Skip writing files (generate only) */
skipWrite?: boolean;
/** Callback for file invalidation */
onInvalidate?: (id: string) => void;
}
interface ChokidarOptions {
ignored?: any;
ignoreInitial?: boolean;
followSymlinks?: boolean;
cwd?: string;
disableGlobbing?: boolean;
usePolling?: boolean;
interval?: number;
binaryInterval?: number;
alwaysStat?: boolean;
depth?: number;
awaitWriteFinish?: boolean | { stabilityThreshold?: number; pollInterval?: number };
ignorePermissionErrors?: boolean;
atomic?: boolean | number;
persistent?: boolean;
useFsEvents?: boolean;
}export default defineConfig([
// ES Module build
{
input: "src/index.ts",
external: ["react", "lodash"],
output: {
file: "dist/index.esm.js",
format: "esm",
sourcemap: true
},
plugins: [typescript()]
},
// CommonJS build
{
input: "src/index.ts",
external: ["react", "lodash"],
output: {
file: "dist/index.cjs.js",
format: "cjs",
exports: "named",
sourcemap: true
},
plugins: [typescript()]
},
// UMD build
{
input: "src/index.ts",
output: {
file: "dist/index.umd.js",
format: "umd",
name: "MyLibrary",
globals: {
react: "React",
lodash: "_"
}
},
plugins: [typescript(), resolve(), commonjs()]
}
]);export default defineConfig((args) => {
const isProduction = !args.watch;
const isDevelopment = args.watch;
return {
input: "src/main.js",
output: {
file: "dist/bundle.js",
format: "esm",
sourcemap: isDevelopment
},
plugins: [
resolve(),
commonjs(),
...(isProduction ? [terser()] : []),
...(isDevelopment ? [livereload()] : [])
],
treeshake: isProduction ? "recommended" : false
};
});Install with Tessl CLI
npx tessl i tessl/npm-rollup