0
# Metro Babel Transformer
1
2
Metro Babel Transformer is the base Babel transformation engine for Metro bundler, providing JavaScript and TypeScript code transformation capabilities. It supports dual parser modes (Babel or Hermes), configurable transformation options, and generates AST output with metadata for Metro's bundling pipeline.
3
4
## Package Information
5
6
- **Package Name**: metro-babel-transformer
7
- **Package Type**: npm
8
- **Language**: JavaScript (with Flow types)
9
- **Installation**: `npm install metro-babel-transformer`
10
11
## Core Imports
12
13
```javascript
14
const { transform } = require("metro-babel-transformer");
15
```
16
17
For TypeScript users:
18
19
```typescript
20
import { transform, BabelTransformerArgs, BabelTransformerOptions } from "metro-babel-transformer";
21
import type { File as BabelNodeFile } from "@babel/types";
22
```
23
24
## Basic Usage
25
26
```javascript
27
const { transform } = require("metro-babel-transformer");
28
29
// Transform JavaScript source code
30
const result = transform({
31
filename: "example.js",
32
src: `
33
const greeting = (name) => {
34
return \`Hello, \${name}!\`;
35
};
36
export default greeting;
37
`,
38
options: {
39
dev: true,
40
enableBabelRuntime: false,
41
enableBabelRCLookup: false,
42
globalPrefix: "__metro__",
43
hot: false,
44
inlineRequires: undefined, // Reserved for future use
45
minify: false,
46
platform: null,
47
publicPath: "/assets",
48
projectRoot: "/path/to/project",
49
},
50
plugins: [
51
// Optional Babel plugins array
52
["@babel/plugin-transform-modules-commonjs", {}],
53
],
54
});
55
56
console.log("Transformed AST:", result.ast);
57
console.log("Metadata:", result.metadata);
58
```
59
60
## Architecture
61
62
Metro Babel Transformer is designed around several key concepts:
63
64
- **Transform Function**: Core transformation engine that processes source code through Babel
65
- **Dual Parser Support**: Can use either Babel's parser or Hermes parser for JavaScript parsing
66
- **Environment Management**: Automatically configures BABEL_ENV based on development/production mode
67
- **AST Processing**: Returns transformed Abstract Syntax Tree ready for Metro's bundling pipeline
68
- **Metadata Generation**: Provides transformation metadata for debugging and optimization
69
70
## Capabilities
71
72
### Code Transformation
73
74
Transforms JavaScript and TypeScript source code using Babel with configurable options and plugins.
75
76
```javascript { .api }
77
/**
78
* Transform source code using Babel with configurable options
79
* @param args - Transformation arguments containing source, options, and plugins
80
* @returns Object with transformed AST and metadata
81
*/
82
function transform(args: BabelTransformerArgs): {
83
ast: BabelNodeFile;
84
functionMap?: BabelFileFunctionMapMetadata; // Deprecated - will be removed in future release. Function maps are now generated by Babel plugins and included in metadata.
85
metadata?: MetroBabelFileMetadata;
86
};
87
```
88
89
### Transformer Arguments
90
91
```typescript { .api }
92
interface BabelTransformerArgs {
93
/** Path to the source file being transformed */
94
readonly filename: string;
95
/** Transformer configuration options */
96
readonly options: BabelTransformerOptions;
97
/** Optional array of Babel plugins to apply */
98
readonly plugins?: Array<string | [string, any] | BabelPluginInstance>;
99
/** Source code string to transform */
100
readonly src: string;
101
}
102
```
103
104
### Transformer Options
105
106
```typescript { .api }
107
interface BabelTransformerOptions {
108
/** Custom transform options passed to plugins */
109
readonly customTransformOptions?: CustomTransformOptions;
110
/** Development mode flag - affects BABEL_ENV and optimizations */
111
readonly dev: boolean;
112
/** Enable lookup of .babelrc files */
113
readonly enableBabelRCLookup?: boolean;
114
/** Enable Babel runtime helpers (boolean or specific runtime package) */
115
readonly enableBabelRuntime: boolean | string;
116
/** Path to babel config file to extend */
117
readonly extendsBabelConfigPath?: string;
118
/** Enable experimental import statement support */
119
readonly experimentalImportSupport?: boolean;
120
/** Use Hermes parser instead of Babel parser */
121
readonly hermesParser?: boolean;
122
/** Hot reload mode flag */
123
readonly hot: boolean;
124
/** Inline requires setting (reserved for future use) */
125
readonly inlineRequires?: void;
126
/** Minification flag */
127
readonly minify: boolean;
128
/** Disable ES6 transforms (experimental) */
129
readonly unstable_disableES6Transforms?: boolean;
130
/** Target platform (e.g., 'ios', 'android', 'web') */
131
readonly platform: string | null;
132
/** Project root directory path */
133
readonly projectRoot: string;
134
/** Public path for assets */
135
readonly publicPath: string;
136
/** Transform profile for different optimization levels */
137
readonly unstable_transformProfile?: TransformProfile;
138
/** Global prefix for generated identifiers */
139
readonly globalPrefix: string;
140
}
141
```
142
143
### Transform Profiles
144
145
```typescript { .api }
146
type TransformProfile = 'default' | 'hermes-stable' | 'hermes-canary';
147
```
148
149
### Custom Transform Options
150
151
```typescript { .api }
152
interface CustomTransformOptions {
153
[key: string]: unknown;
154
}
155
```
156
157
### Babel Transformer Interface
158
159
Complete interface for implementing custom transformers compatible with Metro.
160
161
```typescript { .api }
162
interface BabelTransformer {
163
/** Main transform function */
164
transform: (args: BabelTransformerArgs) => {
165
ast: BabelNodeFile;
166
functionMap?: BabelFileFunctionMapMetadata; // Deprecated - will be removed in future release. Function maps are now generated by Babel plugins and included in metadata.
167
metadata?: MetroBabelFileMetadata;
168
};
169
/** Optional cache key generator for caching transformed results */
170
getCacheKey?: () => string;
171
}
172
```
173
174
### External Types
175
176
These types are imported from `@babel/core`:
177
178
```typescript { .api }
179
/** Babel AST node representing a complete file */
180
type BabelNodeFile = import('@babel/types').File;
181
182
/** Base Babel file metadata */
183
interface BabelFileMetadata {
184
[key: string]: any;
185
}
186
187
/** Babel core configuration options */
188
interface BabelCoreOptions {
189
plugins?: Array<string | [string, any] | BabelPluginInstance>;
190
[key: string]: any;
191
}
192
193
/** Babel plugin instance */
194
interface BabelPluginInstance {
195
(babel: any, options?: any): {
196
visitor: any;
197
[key: string]: any;
198
};
199
}
200
```
201
202
### Metadata Types
203
204
```typescript { .api }
205
interface MetroBabelFileMetadata extends BabelFileMetadata {
206
/** Metro-specific metadata extensions */
207
metro?: {
208
/** Function mapping data for debugging */
209
functionMap?: BabelFileFunctionMapMetadata;
210
/** Import declaration locations for optimization */
211
unstable_importDeclarationLocs?: BabelFileImportLocsMetadata;
212
};
213
}
214
215
interface BabelFileFunctionMapMetadata {
216
/** Array of function names in the source */
217
readonly names: ReadonlyArray<string>;
218
/** Source map style mappings for function locations */
219
readonly mappings: string;
220
}
221
222
type BabelFileImportLocsMetadata = ReadonlySet<string>;
223
```
224
225
## Usage Examples
226
227
### Basic Transformation
228
229
```javascript
230
const { transform } = require("metro-babel-transformer");
231
232
const result = transform({
233
filename: "app.js",
234
src: "const app = () => 'Hello World';",
235
options: {
236
dev: false,
237
enableBabelRuntime: false,
238
enableBabelRCLookup: true,
239
globalPrefix: "__app__",
240
hot: false,
241
minify: true,
242
platform: "web",
243
publicPath: "/static",
244
projectRoot: process.cwd(),
245
},
246
});
247
```
248
249
### Hermes Parser Usage
250
251
```javascript
252
const result = transform({
253
filename: "component.js",
254
src: "export const Component = () => <div>React Component</div>;",
255
options: {
256
dev: true,
257
enableBabelRuntime: "@babel/runtime",
258
hermesParser: true, // Use Hermes parser instead of Babel
259
hot: true,
260
minify: false,
261
platform: "ios",
262
projectRoot: "/Users/dev/my-app",
263
publicPath: "/",
264
globalPrefix: "__metro__",
265
},
266
plugins: [
267
["@babel/plugin-transform-react-jsx", { runtime: "automatic" }],
268
],
269
});
270
```
271
272
### With Custom Transform Options
273
274
```javascript
275
const result = transform({
276
filename: "feature.ts",
277
src: "const feature: Feature = { enabled: true };",
278
options: {
279
dev: true,
280
enableBabelRuntime: false,
281
hot: false,
282
minify: false,
283
platform: "android",
284
projectRoot: "/project",
285
publicPath: "/assets",
286
globalPrefix: "__app__",
287
customTransformOptions: {
288
experimentalDecorators: true,
289
strictMode: false,
290
},
291
unstable_transformProfile: "hermes-stable",
292
},
293
});
294
```
295
296
## Error Handling
297
298
The transform function may throw errors in the following scenarios:
299
300
- **Syntax Errors**: When source code contains invalid JavaScript/TypeScript syntax
301
- **Plugin Errors**: When specified Babel plugins encounter configuration or processing errors
302
- **Parser Errors**: When the selected parser (Babel or Hermes) fails to parse the source
303
- **File System Errors**: When babel config files specified in options cannot be read
304
305
Always wrap transform calls in try-catch blocks for production usage:
306
307
```javascript
308
try {
309
const result = transform(transformArgs);
310
// Process result
311
} catch (error) {
312
console.error("Transform failed:", error.message);
313
// Handle transformation error
314
}
315
```