or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-rollup--plugin-alias

A Rollup plugin for defining and resolving aliases when bundling packages

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@rollup/plugin-alias@5.1.x

To install, run

npx @tessl/cli install tessl/npm-rollup--plugin-alias@5.1.0

index.mddocs/

@rollup/plugin-alias

A Rollup plugin for defining and resolving aliases when bundling packages. It enables developers to replace complex relative paths (like ../../../batman) with simple aliases (like batman), similar to Webpack's resolve.alias functionality. The plugin supports both object and array configuration formats, regular expression pattern matching for complex replacements, and custom resolvers for granular control over module resolution.

Package Information

  • Package Name: @rollup/plugin-alias
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @rollup/plugin-alias --save-dev
  • Requirements: Node.js v14.0.0+, Rollup v1.20.0+

Core Imports

import alias from "@rollup/plugin-alias";

For CommonJS:

const alias = require("@rollup/plugin-alias");

Basic Usage

import alias from "@rollup/plugin-alias";

export default {
  input: "src/index.js",
  output: {
    dir: "output",
    format: "cjs"
  },
  plugins: [
    alias({
      entries: [
        { find: "utils", replacement: "../../../utils" },
        { find: "batman-1.0.0", replacement: "./joker-1.5.0" }
      ]
    })
  ]
};

Architecture

The @rollup/plugin-alias plugin operates by intercepting Rollup's module resolution process through the resolveId hook. Here's how it works:

  • Entry Processing: The plugin normalizes configuration entries into a consistent internal format (ResolvedAlias[]), supporting both object and array formats
  • Pattern Matching: During resolution, it sequentially tests import paths against configured patterns (strings or RegExp) using a matches() function
  • Path Replacement: When a match is found, it performs string replacement, supporting regex capture groups for complex transformations
  • Custom Resolution: If a custom resolver is specified (globally or per-alias), it delegates to that resolver; otherwise uses Rollup's default resolution
  • Build Integration: The plugin integrates with Rollup's build lifecycle, calling custom resolver buildStart hooks when specified
  • Warning System: Issues warnings when rewrites result in non-absolute paths that might cause module duplication

The plugin returns different behaviors based on configuration:

  • Empty configuration: Returns a minimal plugin that resolves all imports to null
  • With entries: Returns a full resolver that processes imports through the alias system

Capabilities

Plugin Creation

Creates a Rollup plugin instance for alias resolution.

import type { Plugin } from "rollup";

/**
 * Creates a Rollup plugin for defining aliases when bundling packages
 * @param options - Optional configuration object
 * @returns Rollup plugin with alias resolution capabilities
 * 
 * Note: Returns different plugin structures based on configuration:
 * - Empty/no entries: Returns minimal plugin with name 'alias' and resolveId that returns null
 * - With entries: Returns full plugin with name 'alias', buildStart hook, and resolveId hook
 */
function alias(options?: RollupAliasOptions): Plugin;

Usage Examples:

// Basic usage with object format
const aliasPlugin = alias({
  entries: {
    utils: "../../../utils",
    "batman-1.0.0": "./joker-1.5.0"
  }
});

// Array format with custom resolvers
const aliasPlugin = alias({
  entries: [
    { find: "src", replacement: path.resolve(__dirname, "src") },
    { find: /^@\/(.*)/, replacement: path.resolve(__dirname, "src/$1") }
  ],
  customResolver: resolve({
    extensions: [".mjs", ".js", ".jsx", ".json"]
  })
});

// No configuration (returns empty resolver)
const aliasPlugin = alias();

Regular Expression Aliases

Support for complex pattern matching and partial replacements.

interface Alias {
  /** Pattern to match against imports - string or RegExp */
  find: string | RegExp;
  /** Replacement path or pattern with capture group support */
  replacement: string;
  /** Optional custom resolver for this specific alias */
  customResolver?: ResolverFunction | ResolverObject | null;
}

Usage Examples:

// Remove loader prefix and add extension
alias({
  entries: [
    { find: /^i18n!(.*)/, replacement: "$1.js" }
  ]
});

// Replace file extensions
alias({
  entries: [
    { find: /^(.*)\.js$/, replacement: "$1.alias" }
  ]
});

// Path prefix replacement
alias({
  entries: [
    { find: /^@\/(.*)/, replacement: path.resolve(__dirname, "src/$1") }
  ]
});

Custom Resolvers

Advanced resolution control with custom resolver functions or objects.

import type { PluginHooks, PluginContext, ResolveIdResult, CustomPluginOptions } from "rollup";

/** 
 * Function signature for custom resolvers 
 * Extracted from Rollup's PluginHooks['resolveId'] type
 */
type ResolverFunction = (
  this: PluginContext,
  id: string,
  importer: string | undefined,
  options: {
    assertions: Record<string, string>;
    custom?: CustomPluginOptions;
    isEntry: boolean;
    skipSelf?: boolean;
  }
) => Promise<ResolveIdResult> | ResolveIdResult;

/** Object-based custom resolver with lifecycle hooks */
interface ResolverObject {
  /** Optional build start hook */
  buildStart?: PluginHooks['buildStart'];
  /** Required resolve ID function */
  resolveId: ResolverFunction;
}

Usage Examples:

import resolve from "@rollup/plugin-node-resolve";

// Global custom resolver
alias({
  entries: { src: "./src" },
  customResolver: resolve({
    extensions: [".mjs", ".js", ".jsx", ".json", ".sass", ".scss"]
  })
});

// Per-alias custom resolver
alias({
  entries: [
    {
      find: "components",
      replacement: "./src/components",
      customResolver: resolve({ browser: true })
    }
  ]
});

// Object-based resolver with lifecycle hooks
alias({
  customResolver: {
    buildStart(inputOptions) {
      console.log("Build starting with options:", inputOptions);
    },
    async resolveId(id, importer, options) {
      if (id.startsWith("virtual:")) {
        return { id, virtual: true };
      }
      return null;
    }
  }
});

Configuration Options

Main Configuration Interface

interface RollupAliasOptions {
  /**
   * Global custom resolver applied to all aliases
   * Instructs the plugin to use alternative resolving algorithm
   * rather than Rollup's default resolver
   * @default null
   */
  customResolver?: ResolverFunction | ResolverObject | null;

  /**
   * Alias definitions in object or array format
   * Order matters: first defined rules are applied first
   * @default null
   */
  entries?: readonly Alias[] | { [find: string]: string };
}

Object Format Configuration

Simple key-value mappings for straightforward alias definitions.

/** Simple object format for alias definitions */
type ObjectEntries = { [find: string]: string };

Usage Examples:

alias({
  entries: {
    utils: "../../../utils",
    "batman-1.0.0": "./joker-1.5.0",
    "@": path.resolve(__dirname, "src"),
    "~": path.resolve(__dirname, "assets")
  }
});

Array Format Configuration

Advanced configuration with per-alias custom resolvers.

/** Array format for complex alias configurations */
type ArrayEntries = readonly Alias[];

Usage Examples:

alias({
  entries: [
    { find: "utils", replacement: "../../../utils" },
    { 
      find: "components", 
      replacement: "./src/components",
      customResolver: nodeResolve({ browser: true })
    },
    { find: /^@\/(.*)/, replacement: "src/$1" }
  ]
});

Advanced Usage Patterns

Integration with Other Plugins

import alias from "@rollup/plugin-alias";
import resolve from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";

export default {
  plugins: [
    // Alias should generally come before other resolution plugins
    alias({
      entries: {
        "@": path.resolve(__dirname, "src"),
        "~": path.resolve(__dirname, "assets")
      }
    }),
    resolve(),
    typescript()
  ]
};

Path Resolution Best Practices

import path from "path";

alias({
  entries: [
    // Use absolute paths to avoid module duplication
    { find: "src", replacement: path.resolve(__dirname, "src") },
    
    // RegExp patterns for flexible matching
    { find: /^@\/(.*)/, replacement: path.resolve(__dirname, "src/$1") },
    
    // Environment-specific aliases
    { 
      find: "config", 
      replacement: process.env.NODE_ENV === "production" 
        ? "./config.prod.js" 
        : "./config.dev.js" 
    }
  ]
});

Warning System

The plugin will issue warnings when alias replacements result in non-absolute paths that cannot be resolved by other plugins:

// This may cause warnings if the replacement is not resolved
alias({
  entries: [
    { find: "utils", replacement: "./relative/path/to/utils" } // May warn
  ]
});

// Preferred approach to avoid warnings
alias({
  entries: [
    { find: "utils", replacement: path.resolve(__dirname, "relative/path/to/utils") } // No warnings
  ]
});

The warning message indicates potential module duplication issues and suggests using absolute paths for reliable resolution.

Types

Core Type Definitions

/** Utility type to extract function types from union types */
type MapToFunction<T> = T extends Function ? T : never;

/** Internal resolved alias representation */
interface ResolvedAlias {
  find: string | RegExp;
  replacement: string;
  resolverFunction: ResolverFunction | null;
}