or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# @rollup/plugin-alias

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: @rollup/plugin-alias

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @rollup/plugin-alias --save-dev`

10

- **Requirements**: Node.js v14.0.0+, Rollup v1.20.0+

11

12

## Core Imports

13

14

```typescript

15

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

16

```

17

18

For CommonJS:

19

20

```javascript

21

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

22

```

23

24

## Basic Usage

25

26

```typescript

27

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

28

29

export default {

30

input: "src/index.js",

31

output: {

32

dir: "output",

33

format: "cjs"

34

},

35

plugins: [

36

alias({

37

entries: [

38

{ find: "utils", replacement: "../../../utils" },

39

{ find: "batman-1.0.0", replacement: "./joker-1.5.0" }

40

]

41

})

42

]

43

};

44

```

45

46

## Architecture

47

48

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

49

50

- **Entry Processing**: The plugin normalizes configuration entries into a consistent internal format (`ResolvedAlias[]`), supporting both object and array formats

51

- **Pattern Matching**: During resolution, it sequentially tests import paths against configured patterns (strings or RegExp) using a `matches()` function

52

- **Path Replacement**: When a match is found, it performs string replacement, supporting regex capture groups for complex transformations

53

- **Custom Resolution**: If a custom resolver is specified (globally or per-alias), it delegates to that resolver; otherwise uses Rollup's default resolution

54

- **Build Integration**: The plugin integrates with Rollup's build lifecycle, calling custom resolver `buildStart` hooks when specified

55

- **Warning System**: Issues warnings when rewrites result in non-absolute paths that might cause module duplication

56

57

The plugin returns different behaviors based on configuration:

58

- **Empty configuration**: Returns a minimal plugin that resolves all imports to `null`

59

- **With entries**: Returns a full resolver that processes imports through the alias system

60

61

## Capabilities

62

63

### Plugin Creation

64

65

Creates a Rollup plugin instance for alias resolution.

66

67

```typescript { .api }

68

import type { Plugin } from "rollup";

69

70

/**

71

* Creates a Rollup plugin for defining aliases when bundling packages

72

* @param options - Optional configuration object

73

* @returns Rollup plugin with alias resolution capabilities

74

*

75

* Note: Returns different plugin structures based on configuration:

76

* - Empty/no entries: Returns minimal plugin with name 'alias' and resolveId that returns null

77

* - With entries: Returns full plugin with name 'alias', buildStart hook, and resolveId hook

78

*/

79

function alias(options?: RollupAliasOptions): Plugin;

80

```

81

82

**Usage Examples:**

83

84

```typescript

85

// Basic usage with object format

86

const aliasPlugin = alias({

87

entries: {

88

utils: "../../../utils",

89

"batman-1.0.0": "./joker-1.5.0"

90

}

91

});

92

93

// Array format with custom resolvers

94

const aliasPlugin = alias({

95

entries: [

96

{ find: "src", replacement: path.resolve(__dirname, "src") },

97

{ find: /^@\/(.*)/, replacement: path.resolve(__dirname, "src/$1") }

98

],

99

customResolver: resolve({

100

extensions: [".mjs", ".js", ".jsx", ".json"]

101

})

102

});

103

104

// No configuration (returns empty resolver)

105

const aliasPlugin = alias();

106

```

107

108

### Regular Expression Aliases

109

110

Support for complex pattern matching and partial replacements.

111

112

```typescript { .api }

113

interface Alias {

114

/** Pattern to match against imports - string or RegExp */

115

find: string | RegExp;

116

/** Replacement path or pattern with capture group support */

117

replacement: string;

118

/** Optional custom resolver for this specific alias */

119

customResolver?: ResolverFunction | ResolverObject | null;

120

}

121

```

122

123

**Usage Examples:**

124

125

```typescript

126

// Remove loader prefix and add extension

127

alias({

128

entries: [

129

{ find: /^i18n!(.*)/, replacement: "$1.js" }

130

]

131

});

132

133

// Replace file extensions

134

alias({

135

entries: [

136

{ find: /^(.*)\.js$/, replacement: "$1.alias" }

137

]

138

});

139

140

// Path prefix replacement

141

alias({

142

entries: [

143

{ find: /^@\/(.*)/, replacement: path.resolve(__dirname, "src/$1") }

144

]

145

});

146

```

147

148

### Custom Resolvers

149

150

Advanced resolution control with custom resolver functions or objects.

151

152

```typescript { .api }

153

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

154

155

/**

156

* Function signature for custom resolvers

157

* Extracted from Rollup's PluginHooks['resolveId'] type

158

*/

159

type ResolverFunction = (

160

this: PluginContext,

161

id: string,

162

importer: string | undefined,

163

options: {

164

assertions: Record<string, string>;

165

custom?: CustomPluginOptions;

166

isEntry: boolean;

167

skipSelf?: boolean;

168

}

169

) => Promise<ResolveIdResult> | ResolveIdResult;

170

171

/** Object-based custom resolver with lifecycle hooks */

172

interface ResolverObject {

173

/** Optional build start hook */

174

buildStart?: PluginHooks['buildStart'];

175

/** Required resolve ID function */

176

resolveId: ResolverFunction;

177

}

178

```

179

180

**Usage Examples:**

181

182

```typescript

183

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

184

185

// Global custom resolver

186

alias({

187

entries: { src: "./src" },

188

customResolver: resolve({

189

extensions: [".mjs", ".js", ".jsx", ".json", ".sass", ".scss"]

190

})

191

});

192

193

// Per-alias custom resolver

194

alias({

195

entries: [

196

{

197

find: "components",

198

replacement: "./src/components",

199

customResolver: resolve({ browser: true })

200

}

201

]

202

});

203

204

// Object-based resolver with lifecycle hooks

205

alias({

206

customResolver: {

207

buildStart(inputOptions) {

208

console.log("Build starting with options:", inputOptions);

209

},

210

async resolveId(id, importer, options) {

211

if (id.startsWith("virtual:")) {

212

return { id, virtual: true };

213

}

214

return null;

215

}

216

}

217

});

218

```

219

220

## Configuration Options

221

222

### Main Configuration Interface

223

224

```typescript { .api }

225

interface RollupAliasOptions {

226

/**

227

* Global custom resolver applied to all aliases

228

* Instructs the plugin to use alternative resolving algorithm

229

* rather than Rollup's default resolver

230

* @default null

231

*/

232

customResolver?: ResolverFunction | ResolverObject | null;

233

234

/**

235

* Alias definitions in object or array format

236

* Order matters: first defined rules are applied first

237

* @default null

238

*/

239

entries?: readonly Alias[] | { [find: string]: string };

240

}

241

```

242

243

### Object Format Configuration

244

245

Simple key-value mappings for straightforward alias definitions.

246

247

```typescript { .api }

248

/** Simple object format for alias definitions */

249

type ObjectEntries = { [find: string]: string };

250

```

251

252

**Usage Examples:**

253

254

```typescript

255

alias({

256

entries: {

257

utils: "../../../utils",

258

"batman-1.0.0": "./joker-1.5.0",

259

"@": path.resolve(__dirname, "src"),

260

"~": path.resolve(__dirname, "assets")

261

}

262

});

263

```

264

265

### Array Format Configuration

266

267

Advanced configuration with per-alias custom resolvers.

268

269

```typescript { .api }

270

/** Array format for complex alias configurations */

271

type ArrayEntries = readonly Alias[];

272

```

273

274

**Usage Examples:**

275

276

```typescript

277

alias({

278

entries: [

279

{ find: "utils", replacement: "../../../utils" },

280

{

281

find: "components",

282

replacement: "./src/components",

283

customResolver: nodeResolve({ browser: true })

284

},

285

{ find: /^@\/(.*)/, replacement: "src/$1" }

286

]

287

});

288

```

289

290

## Advanced Usage Patterns

291

292

### Integration with Other Plugins

293

294

```typescript

295

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

296

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

297

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

298

299

export default {

300

plugins: [

301

// Alias should generally come before other resolution plugins

302

alias({

303

entries: {

304

"@": path.resolve(__dirname, "src"),

305

"~": path.resolve(__dirname, "assets")

306

}

307

}),

308

resolve(),

309

typescript()

310

]

311

};

312

```

313

314

### Path Resolution Best Practices

315

316

```typescript

317

import path from "path";

318

319

alias({

320

entries: [

321

// Use absolute paths to avoid module duplication

322

{ find: "src", replacement: path.resolve(__dirname, "src") },

323

324

// RegExp patterns for flexible matching

325

{ find: /^@\/(.*)/, replacement: path.resolve(__dirname, "src/$1") },

326

327

// Environment-specific aliases

328

{

329

find: "config",

330

replacement: process.env.NODE_ENV === "production"

331

? "./config.prod.js"

332

: "./config.dev.js"

333

}

334

]

335

});

336

```

337

338

### Warning System

339

340

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

341

342

```typescript

343

// This may cause warnings if the replacement is not resolved

344

alias({

345

entries: [

346

{ find: "utils", replacement: "./relative/path/to/utils" } // May warn

347

]

348

});

349

350

// Preferred approach to avoid warnings

351

alias({

352

entries: [

353

{ find: "utils", replacement: path.resolve(__dirname, "relative/path/to/utils") } // No warnings

354

]

355

});

356

```

357

358

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

359

360

## Types

361

362

### Core Type Definitions

363

364

```typescript { .api }

365

/** Utility type to extract function types from union types */

366

type MapToFunction<T> = T extends Function ? T : never;

367

368

/** Internal resolved alias representation */

369

interface ResolvedAlias {

370

find: string | RegExp;

371

replacement: string;

372

resolverFunction: ResolverFunction | null;

373

}

374

```