A Rollup plugin for defining and resolving aliases when bundling packages
npx @tessl/cli install tessl/npm-rollup--plugin-alias@5.1.0A 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.
npm install @rollup/plugin-alias --save-devimport alias from "@rollup/plugin-alias";For CommonJS:
const alias = require("@rollup/plugin-alias");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" }
]
})
]
};The @rollup/plugin-alias plugin operates by intercepting Rollup's module resolution process through the resolveId hook. Here's how it works:
ResolvedAlias[]), supporting both object and array formatsmatches() functionbuildStart hooks when specifiedThe plugin returns different behaviors based on configuration:
nullCreates 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();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") }
]
});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;
}
}
});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 };
}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")
}
});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" }
]
});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()
]
};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"
}
]
});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.
/** 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;
}