CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rollup-plugin-babel

Seamless integration between Rollup and Babel for transpiling ES6/7+ code during bundling

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

rollup-plugin-babel

rollup-plugin-babel provides seamless integration between Rollup (JavaScript module bundler) and Babel (JavaScript transpiler), enabling developers to transform ES6/7+ code during the bundling process. It automatically deduplicates Babel helpers, supports both Babel 6 and 7, and handles complex scenarios like external dependencies and runtime helpers.

Package Information

  • Package Name: rollup-plugin-babel
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install --save-dev rollup-plugin-babel@latest

Core Imports

import babel from "rollup-plugin-babel";

For CommonJS:

const babel = require("rollup-plugin-babel");

Basic Usage

import { rollup } from "rollup";
import babel from "rollup-plugin-babel";

// Modern Rollup (1.x+)
rollup({
  input: "main.js",
  plugins: [
    babel({
      exclude: "node_modules/**"
    })
  ]
}).then(bundle => {
  // Bundle is ready
});

// Legacy Rollup (0.x)
rollup({
  entry: "main.js",  // 'entry' was used instead of 'input'
  plugins: [
    babel({
      exclude: "node_modules/**"
    })
  ]
});

Architecture

rollup-plugin-babel is built around several key components:

  • Plugin Factory: Main function that creates Rollup plugins configured with Babel options
  • Custom Builder: Advanced utility for creating custom plugin configurations with hooks
  • Helper Management: Automatic deduplication of Babel helpers to optimize bundle size
  • Configuration System: Flexible options for filtering files, managing helpers, and Babel integration
  • Compatibility Layer: Support for both Babel 6 and 7 with appropriate validation

Capabilities

Plugin Factory

Creates a Rollup plugin for Babel transpilation with comprehensive configuration options.

/**
 * Creates a Rollup plugin for Babel transpilation
 * @param {BabelPluginOptions} options - Configuration options
 * @returns {RollupPlugin} Configured Rollup plugin
 */
function babel(options?: BabelPluginOptions): RollupPlugin;

interface BabelPluginOptions {
  /** File extensions to transpile (default: babel.DEFAULT_EXTENSIONS: ['.js', '.jsx', '.es6', '.es', '.mjs']) */
  extensions?: string[];
  /** Minimatch pattern(s) for files to include */
  include?: string | RegExp | Array<string | RegExp>;
  /** Minimatch pattern(s) for files to exclude */
  exclude?: string | RegExp | Array<string | RegExp>;
  /** Whether to use external Babel helpers via global babelHelpers object (default: false) */
  externalHelpers?: boolean;
  /** Whitelist specific external helpers when using externalHelpers */
  externalHelpersWhitelist?: string[];
  /** Whether to use @babel/plugin-transform-runtime helpers (default: false) */
  runtimeHelpers?: boolean;
  /** Enable sourcemaps - all variants map to same option (default: true) */
  sourcemap?: boolean;
  sourcemaps?: boolean;
  sourceMap?: boolean;
  sourceMaps?: boolean;
  /** Standard Babel configuration options */
  plugins?: any[];
  presets?: any[];
  babelrc?: boolean;
  /** Any other Babel configuration options */
  [key: string]: any;
}

interface RollupPlugin {
  name: string;
  resolveId?(id: string): string | null;
  load?(id: string): string | null;
  transform?(code: string, id: string): Promise<TransformResult | null>;
}

interface TransformResult {
  code: string;
  map?: any;
}

Usage Examples:

// Basic configuration
babel({
  exclude: "node_modules/**",
  presets: [["@babel/preset-env", { modules: false }]]
})

// With external helpers
babel({
  externalHelpers: true,
  plugins: ["external-helpers"]
})

// Runtime helpers configuration
babel({
  runtimeHelpers: true,
  plugins: ["@babel/plugin-transform-runtime"]
})

// File filtering
babel({
  include: ["src/**/*"],
  exclude: ["src/**/*.test.js"],
  extensions: [".js", ".jsx", ".ts", ".tsx"]
})

Custom Plugin Builder

Advanced utility for creating custom Babel plugin configurations with lifecycle hooks.

/**
 * Creates a custom plugin builder with advanced configuration hooks
 * @param {CustomCallback} callback - Callback that receives babel core instance
 * @returns {PluginFactory} Custom plugin factory function
 */
function custom(callback: CustomCallback): PluginFactory;

type CustomCallback = (babelCore: typeof import('@babel/core')) => CustomHooks;

interface CustomHooks {
  /** 
   * Modify plugin options before processing. Must be synchronous.
   * @param pluginOptions - Raw options passed to the plugin
   * @returns Object with customOptions and pluginOptions
   */
  options?(pluginOptions: any): OptionsResult;
  /** 
   * Modify Babel configuration per file
   * @param cfg - Babel's PartialConfig object
   * @param context - Contains code and customOptions
   * @returns Modified Babel options object
   */
  config?(cfg: PartialConfig, context: ConfigContext): any;
  /** 
   * Modify transformation result after Babel processing
   * @param result - Babel transformation result
   * @param context - Contains code, customOptions, config, and transformOptions
   * @returns Modified transformation result
   */
  result?(result: TransformResult, context: ResultContext): TransformResult;
}

interface OptionsResult {
  /** Custom options to pass to config and result hooks */
  customOptions?: any;
  /** Processed plugin options to pass to Babel */
  pluginOptions: any;
}

interface ConfigContext {
  /** Source code being transformed */
  code: string;
  /** Custom options returned from options hook */
  customOptions: any;
}

interface ResultContext {
  /** Source code being transformed */
  code: string;
  /** Custom options returned from options hook */
  customOptions: any;
  /** Babel configuration object */
  config: any;
  /** Final Babel transform options */
  transformOptions: any;
}

interface PartialConfig {
  /** Check if Babel found a filesystem config (.babelrc, babel.config.js, etc.) */
  hasFilesystemConfig(): boolean;
  /** Babel configuration options */
  options: any;
}

type PluginFactory = (options?: any) => RollupPlugin;

Usage Examples:

// Custom plugin with configuration hooks
const customBabel = babel.custom(babelCore => ({
  options(opts) {
    const { customOpt, ...pluginOptions } = opts;
    return {
      customOptions: { customOpt },
      pluginOptions
    };
  },
  
  config(cfg, { code, customOptions }) {
    if (cfg.hasFilesystemConfig()) {
      return cfg.options;
    }
    
    return {
      ...cfg.options,
      plugins: [
        ...(cfg.options.plugins || []),
        myCustomPlugin
      ]
    };
  },
  
  result(result, { customOptions }) {
    return {
      ...result,
      code: result.code + "\\n// Generated with custom transforms"
    };
  }
}));

// Use the custom plugin
export default {
  plugins: [customBabel({ customOpt: true })]
};

Configuration Details

Helper Management

The plugin automatically manages Babel helpers to optimize bundle size through three strategies:

  • Inline Helpers (default): Helper functions are included directly in each transformed file. The plugin automatically deduplicates these helpers, combining them in a single block at the top of your bundle.
  • External Helpers: Helpers reference a global babelHelpers object. Use with externalHelpers: true and the external-helpers plugin.
  • Runtime Helpers: Helpers are imported from @babel/runtime. Use with runtimeHelpers: true and @babel/plugin-transform-runtime.

Automatic Helper Deduplication: Unlike manual Babel compilation, rollup-plugin-babel automatically deduplicates inline helpers across all modules, preventing code duplication even when helpers are used in multiple files.

// External helpers configuration
babel({
  externalHelpers: true,
  plugins: ["external-helpers"]
})

// Runtime helpers (requires @babel/plugin-transform-runtime)
babel({
  runtimeHelpers: true,
  plugins: ["@babel/plugin-transform-runtime"]
})

File Filtering

Control which files are processed using include/exclude patterns and extensions:

babel({
  // Process only source files
  include: ["src/**/*"],
  // Skip test files and node_modules
  exclude: ["**/*.test.js", "node_modules/**"],
  // Support additional extensions
  extensions: [".js", ".jsx", ".ts", ".tsx"]
})

Babel Configuration

The plugin respects .babelrc files and supports all standard Babel options:

babel({
  // Disable .babelrc lookup
  babelrc: false,
  // Inline preset configuration
  presets: [["@babel/preset-env", { modules: false }]],
  // Plugin configuration
  plugins: ["@babel/plugin-proposal-class-properties"]
})

Error Handling

The plugin includes a preflight check system that validates Babel configuration before processing files:

Preflight Check System

The plugin automatically tests Babel configuration by transforming a sample class to detect:

  • Whether ES6 module syntax is preserved (required for Rollup)
  • What type of helper system is being used (inline, external, or runtime)

Common Errors

Module Transform Error:

Rollup requires that your Babel configuration keeps ES6 module syntax intact.
Unfortunately it looks like your configuration specifies a module transformer
to replace ES6 modules with another module format.

Solution: Add modules: false to your @babel/preset-env configuration

Runtime Helpers Error:

Runtime helpers are not enabled. Either exclude the transform-runtime Babel plugin 
or pass the `runtimeHelpers: true` option.

Solution: Set runtimeHelpers: true when using @babel/plugin-transform-runtime

Async Options Hook Error:

.options hook can't be asynchronous. It should return { customOptions, pluginsOptions } synchronously.

Solution: Ensure custom plugin options hooks return objects directly, not Promises

Compatibility

  • Babel Support: Babel 7.x (peer dependency: 7 || ^7.0.0-rc.2)
  • Rollup Support: Rollup 0.60.0 and above (peer dependency: >=0.60.0 <3)
  • Node.js: Compatible with all Node.js versions supported by Babel and Rollup
  • Legacy Support: Babel 6.x support available in rollup-plugin-babel@3

Performance Considerations

  • Use exclude: "node_modules/**" to avoid transpiling dependencies
  • Enable externalHelpers for projects with many modules to reduce bundle size
  • Consider runtimeHelpers for applications that can include @babel/runtime as a dependency
  • File filtering with include/exclude patterns can significantly impact build performance

Common Use Cases

Standard ES6+ Transpilation

babel({
  exclude: "node_modules/**",
  presets: [["@babel/preset-env", { modules: false }]]
})

TypeScript Support

babel({
  extensions: [".js", ".jsx", ".ts", ".tsx"],
  presets: ["@babel/preset-typescript"]
})

React Applications

babel({
  exclude: "node_modules/**",
  presets: [
    ["@babel/preset-env", { modules: false }],
    "@babel/preset-react"
  ]
})

Library Development

babel({
  externalHelpers: true,
  exclude: "node_modules/**",
  plugins: ["external-helpers"]
})
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/rollup-plugin-babel@4.4.x
Publish Source
CLI
Badge
tessl/npm-rollup-plugin-babel badge