0
# rollup-plugin-babel
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: rollup-plugin-babel
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install --save-dev rollup-plugin-babel@latest`
10
11
## Core Imports
12
13
```javascript
14
import babel from "rollup-plugin-babel";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const babel = require("rollup-plugin-babel");
21
```
22
23
## Basic Usage
24
25
```javascript
26
import { rollup } from "rollup";
27
import babel from "rollup-plugin-babel";
28
29
// Modern Rollup (1.x+)
30
rollup({
31
input: "main.js",
32
plugins: [
33
babel({
34
exclude: "node_modules/**"
35
})
36
]
37
}).then(bundle => {
38
// Bundle is ready
39
});
40
41
// Legacy Rollup (0.x)
42
rollup({
43
entry: "main.js", // 'entry' was used instead of 'input'
44
plugins: [
45
babel({
46
exclude: "node_modules/**"
47
})
48
]
49
});
50
```
51
52
## Architecture
53
54
rollup-plugin-babel is built around several key components:
55
56
- **Plugin Factory**: Main function that creates Rollup plugins configured with Babel options
57
- **Custom Builder**: Advanced utility for creating custom plugin configurations with hooks
58
- **Helper Management**: Automatic deduplication of Babel helpers to optimize bundle size
59
- **Configuration System**: Flexible options for filtering files, managing helpers, and Babel integration
60
- **Compatibility Layer**: Support for both Babel 6 and 7 with appropriate validation
61
62
## Capabilities
63
64
### Plugin Factory
65
66
Creates a Rollup plugin for Babel transpilation with comprehensive configuration options.
67
68
```javascript { .api }
69
/**
70
* Creates a Rollup plugin for Babel transpilation
71
* @param {BabelPluginOptions} options - Configuration options
72
* @returns {RollupPlugin} Configured Rollup plugin
73
*/
74
function babel(options?: BabelPluginOptions): RollupPlugin;
75
76
interface BabelPluginOptions {
77
/** File extensions to transpile (default: babel.DEFAULT_EXTENSIONS: ['.js', '.jsx', '.es6', '.es', '.mjs']) */
78
extensions?: string[];
79
/** Minimatch pattern(s) for files to include */
80
include?: string | RegExp | Array<string | RegExp>;
81
/** Minimatch pattern(s) for files to exclude */
82
exclude?: string | RegExp | Array<string | RegExp>;
83
/** Whether to use external Babel helpers via global babelHelpers object (default: false) */
84
externalHelpers?: boolean;
85
/** Whitelist specific external helpers when using externalHelpers */
86
externalHelpersWhitelist?: string[];
87
/** Whether to use @babel/plugin-transform-runtime helpers (default: false) */
88
runtimeHelpers?: boolean;
89
/** Enable sourcemaps - all variants map to same option (default: true) */
90
sourcemap?: boolean;
91
sourcemaps?: boolean;
92
sourceMap?: boolean;
93
sourceMaps?: boolean;
94
/** Standard Babel configuration options */
95
plugins?: any[];
96
presets?: any[];
97
babelrc?: boolean;
98
/** Any other Babel configuration options */
99
[key: string]: any;
100
}
101
102
interface RollupPlugin {
103
name: string;
104
resolveId?(id: string): string | null;
105
load?(id: string): string | null;
106
transform?(code: string, id: string): Promise<TransformResult | null>;
107
}
108
109
interface TransformResult {
110
code: string;
111
map?: any;
112
}
113
```
114
115
**Usage Examples:**
116
117
```javascript
118
// Basic configuration
119
babel({
120
exclude: "node_modules/**",
121
presets: [["@babel/preset-env", { modules: false }]]
122
})
123
124
// With external helpers
125
babel({
126
externalHelpers: true,
127
plugins: ["external-helpers"]
128
})
129
130
// Runtime helpers configuration
131
babel({
132
runtimeHelpers: true,
133
plugins: ["@babel/plugin-transform-runtime"]
134
})
135
136
// File filtering
137
babel({
138
include: ["src/**/*"],
139
exclude: ["src/**/*.test.js"],
140
extensions: [".js", ".jsx", ".ts", ".tsx"]
141
})
142
```
143
144
### Custom Plugin Builder
145
146
Advanced utility for creating custom Babel plugin configurations with lifecycle hooks.
147
148
```javascript { .api }
149
/**
150
* Creates a custom plugin builder with advanced configuration hooks
151
* @param {CustomCallback} callback - Callback that receives babel core instance
152
* @returns {PluginFactory} Custom plugin factory function
153
*/
154
function custom(callback: CustomCallback): PluginFactory;
155
156
type CustomCallback = (babelCore: typeof import('@babel/core')) => CustomHooks;
157
158
interface CustomHooks {
159
/**
160
* Modify plugin options before processing. Must be synchronous.
161
* @param pluginOptions - Raw options passed to the plugin
162
* @returns Object with customOptions and pluginOptions
163
*/
164
options?(pluginOptions: any): OptionsResult;
165
/**
166
* Modify Babel configuration per file
167
* @param cfg - Babel's PartialConfig object
168
* @param context - Contains code and customOptions
169
* @returns Modified Babel options object
170
*/
171
config?(cfg: PartialConfig, context: ConfigContext): any;
172
/**
173
* Modify transformation result after Babel processing
174
* @param result - Babel transformation result
175
* @param context - Contains code, customOptions, config, and transformOptions
176
* @returns Modified transformation result
177
*/
178
result?(result: TransformResult, context: ResultContext): TransformResult;
179
}
180
181
interface OptionsResult {
182
/** Custom options to pass to config and result hooks */
183
customOptions?: any;
184
/** Processed plugin options to pass to Babel */
185
pluginOptions: any;
186
}
187
188
interface ConfigContext {
189
/** Source code being transformed */
190
code: string;
191
/** Custom options returned from options hook */
192
customOptions: any;
193
}
194
195
interface ResultContext {
196
/** Source code being transformed */
197
code: string;
198
/** Custom options returned from options hook */
199
customOptions: any;
200
/** Babel configuration object */
201
config: any;
202
/** Final Babel transform options */
203
transformOptions: any;
204
}
205
206
interface PartialConfig {
207
/** Check if Babel found a filesystem config (.babelrc, babel.config.js, etc.) */
208
hasFilesystemConfig(): boolean;
209
/** Babel configuration options */
210
options: any;
211
}
212
213
type PluginFactory = (options?: any) => RollupPlugin;
214
```
215
216
**Usage Examples:**
217
218
```javascript
219
// Custom plugin with configuration hooks
220
const customBabel = babel.custom(babelCore => ({
221
options(opts) {
222
const { customOpt, ...pluginOptions } = opts;
223
return {
224
customOptions: { customOpt },
225
pluginOptions
226
};
227
},
228
229
config(cfg, { code, customOptions }) {
230
if (cfg.hasFilesystemConfig()) {
231
return cfg.options;
232
}
233
234
return {
235
...cfg.options,
236
plugins: [
237
...(cfg.options.plugins || []),
238
myCustomPlugin
239
]
240
};
241
},
242
243
result(result, { customOptions }) {
244
return {
245
...result,
246
code: result.code + "\\n// Generated with custom transforms"
247
};
248
}
249
}));
250
251
// Use the custom plugin
252
export default {
253
plugins: [customBabel({ customOpt: true })]
254
};
255
```
256
257
## Configuration Details
258
259
### Helper Management
260
261
The plugin automatically manages Babel helpers to optimize bundle size through three strategies:
262
263
- **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.
264
- **External Helpers**: Helpers reference a global `babelHelpers` object. Use with `externalHelpers: true` and the external-helpers plugin.
265
- **Runtime Helpers**: Helpers are imported from @babel/runtime. Use with `runtimeHelpers: true` and @babel/plugin-transform-runtime.
266
267
**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.
268
269
```javascript
270
// External helpers configuration
271
babel({
272
externalHelpers: true,
273
plugins: ["external-helpers"]
274
})
275
276
// Runtime helpers (requires @babel/plugin-transform-runtime)
277
babel({
278
runtimeHelpers: true,
279
plugins: ["@babel/plugin-transform-runtime"]
280
})
281
```
282
283
### File Filtering
284
285
Control which files are processed using include/exclude patterns and extensions:
286
287
```javascript
288
babel({
289
// Process only source files
290
include: ["src/**/*"],
291
// Skip test files and node_modules
292
exclude: ["**/*.test.js", "node_modules/**"],
293
// Support additional extensions
294
extensions: [".js", ".jsx", ".ts", ".tsx"]
295
})
296
```
297
298
### Babel Configuration
299
300
The plugin respects `.babelrc` files and supports all standard Babel options:
301
302
```javascript
303
babel({
304
// Disable .babelrc lookup
305
babelrc: false,
306
// Inline preset configuration
307
presets: [["@babel/preset-env", { modules: false }]],
308
// Plugin configuration
309
plugins: ["@babel/plugin-proposal-class-properties"]
310
})
311
```
312
313
## Error Handling
314
315
The plugin includes a preflight check system that validates Babel configuration before processing files:
316
317
### Preflight Check System
318
319
The plugin automatically tests Babel configuration by transforming a sample class to detect:
320
- Whether ES6 module syntax is preserved (required for Rollup)
321
- What type of helper system is being used (inline, external, or runtime)
322
323
### Common Errors
324
325
**Module Transform Error**:
326
```
327
Rollup requires that your Babel configuration keeps ES6 module syntax intact.
328
Unfortunately it looks like your configuration specifies a module transformer
329
to replace ES6 modules with another module format.
330
```
331
*Solution*: Add `modules: false` to your @babel/preset-env configuration
332
333
**Runtime Helpers Error**:
334
```
335
Runtime helpers are not enabled. Either exclude the transform-runtime Babel plugin
336
or pass the `runtimeHelpers: true` option.
337
```
338
*Solution*: Set `runtimeHelpers: true` when using @babel/plugin-transform-runtime
339
340
**Async Options Hook Error**:
341
```
342
.options hook can't be asynchronous. It should return { customOptions, pluginsOptions } synchronously.
343
```
344
*Solution*: Ensure custom plugin options hooks return objects directly, not Promises
345
346
## Compatibility
347
348
- **Babel Support**: Babel 7.x (peer dependency: `7 || ^7.0.0-rc.2`)
349
- **Rollup Support**: Rollup 0.60.0 and above (peer dependency: `>=0.60.0 <3`)
350
- **Node.js**: Compatible with all Node.js versions supported by Babel and Rollup
351
- **Legacy Support**: Babel 6.x support available in rollup-plugin-babel@3
352
353
## Performance Considerations
354
355
- Use `exclude: "node_modules/**"` to avoid transpiling dependencies
356
- Enable `externalHelpers` for projects with many modules to reduce bundle size
357
- Consider `runtimeHelpers` for applications that can include @babel/runtime as a dependency
358
- File filtering with `include`/`exclude` patterns can significantly impact build performance
359
360
## Common Use Cases
361
362
### Standard ES6+ Transpilation
363
364
```javascript
365
babel({
366
exclude: "node_modules/**",
367
presets: [["@babel/preset-env", { modules: false }]]
368
})
369
```
370
371
### TypeScript Support
372
373
```javascript
374
babel({
375
extensions: [".js", ".jsx", ".ts", ".tsx"],
376
presets: ["@babel/preset-typescript"]
377
})
378
```
379
380
### React Applications
381
382
```javascript
383
babel({
384
exclude: "node_modules/**",
385
presets: [
386
["@babel/preset-env", { modules: false }],
387
"@babel/preset-react"
388
]
389
})
390
```
391
392
### Library Development
393
394
```javascript
395
babel({
396
externalHelpers: true,
397
exclude: "node_modules/**",
398
plugins: ["external-helpers"]
399
})
400
```