0
# Core Transformation
1
2
The core transformation pipeline handles JavaScript, TypeScript, JSX, JSON, and asset file processing through Metro's comprehensive Babel-based transformation system.
3
4
## Capabilities
5
6
### Transform Function
7
8
Main transformation function that processes files through Metro's complete pipeline including parsing, Babel transformation, dependency collection, module wrapping, optimization, and source map generation.
9
10
```javascript { .api }
11
/**
12
* Transform files through Metro's complete transformation pipeline
13
* @param config - Transformer configuration object containing Babel, minifier, and asset settings
14
* @param projectRoot - Absolute path to project root directory
15
* @param filename - Relative path to file being transformed (used for source maps and error reporting)
16
* @param data - File content as Buffer
17
* @param options - Transformation options including dev mode, platform, and optimization settings
18
* @returns Promise resolving to transformation result with dependencies and output
19
*/
20
function transform(
21
config: JsTransformerConfig,
22
projectRoot: string,
23
filename: string,
24
data: Buffer,
25
options: JsTransformOptions
26
): Promise<TransformResponse>;
27
```
28
29
**Usage Examples:**
30
31
```javascript
32
const { transform } = require("metro-transform-worker");
33
const fs = require("fs");
34
35
// Transform a React Native component
36
const config = {
37
babelTransformerPath: require.resolve("@react-native/metro-babel-transformer"),
38
minifierPath: require.resolve("metro-minify-terser"),
39
assetRegistryPath: "react-native/Libraries/Image/AssetRegistry",
40
assetPlugins: [],
41
enableBabelRCLookup: true,
42
enableBabelRuntime: false,
43
globalPrefix: "",
44
hermesParser: false,
45
minifierConfig: {},
46
optimizationSizeLimit: 150000,
47
publicPath: "/assets",
48
allowOptionalDependencies: "ignore",
49
unstable_disableModuleWrapping: false,
50
unstable_compactOutput: false,
51
unstable_allowRequireContext: false,
52
};
53
54
const options = {
55
dev: true,
56
hot: false,
57
inlinePlatform: false,
58
inlineRequires: false,
59
minify: false,
60
platform: "ios",
61
type: "module",
62
unstable_transformProfile: "default",
63
};
64
65
// Transform JavaScript/JSX file
66
const jsFile = fs.readFileSync("./src/components/Button.js");
67
const jsResult = await transform(
68
config,
69
process.cwd(),
70
"./src/components/Button.js",
71
jsFile,
72
options
73
);
74
75
console.log(jsResult.output[0].data.code); // Transformed code
76
console.log(jsResult.dependencies); // Array of module dependencies
77
78
// Transform JSON file
79
const jsonFile = fs.readFileSync("./data/config.json");
80
const jsonResult = await transform(
81
config,
82
process.cwd(),
83
"./data/config.json",
84
jsonFile,
85
{ ...options, type: "module" }
86
);
87
88
// Transform asset file
89
const imageFile = fs.readFileSync("./assets/logo.png");
90
const assetResult = await transform(
91
config,
92
process.cwd(),
93
"./assets/logo.png",
94
imageFile,
95
{ ...options, type: "asset" }
96
);
97
```
98
99
### Transformation Pipeline Stages
100
101
The transformation process includes several key stages:
102
103
#### 1. File Type Detection and Parsing
104
- **JavaScript/JSX/TypeScript**: Parsed using Babylon parser with AST generation
105
- **JSON**: Direct content processing and CommonJS wrapping
106
- **Assets**: Metadata extraction and asset registry integration
107
108
#### 2. Babel Transformation
109
- Plugin-based transformations through configured Babel transformer
110
- Import/export handling with optional experimental import support
111
- Platform-specific code inlining and optimization
112
113
#### 3. Dependency Collection
114
- Module dependency analysis and extraction
115
- Dynamic require handling with configurable behavior
116
- Import/export statement processing
117
118
#### 4. Module Wrapping
119
- CommonJS module wrapping with dependency injection
120
- Script vs module handling for different execution contexts
121
- Global prefix application and scoping
122
123
#### 5. Optimization
124
- Constant folding in production builds
125
- Inline require transformations for performance
126
- Pseudo-global normalization for minification
127
128
#### 6. Source Map Generation
129
- Comprehensive source map creation throughout pipeline
130
- Function map generation for debugging
131
- Segment-based mapping for efficient storage
132
133
### File Type Processing
134
135
#### JavaScript/JSX/TypeScript Files
136
137
Processed through the complete Babel transformation pipeline with full AST manipulation, dependency analysis, and optimization.
138
139
```javascript { .api }
140
// Input file type for JS/JSX/TS processing
141
interface JSFile {
142
filename: string;
143
inputFileSize: number;
144
code: string;
145
type: JSFileType;
146
ast?: BabelNodeFile;
147
functionMap: FBSourceFunctionMap | null;
148
unstable_importDeclarationLocs?: Set<string>;
149
}
150
```
151
152
**Processing steps:**
153
1. AST parsing with Babylon
154
2. "use strict" directive injection for modules
155
3. Babel plugin transformations (import/export, inline requires, platform inlining)
156
4. Constant folding optimization (production only)
157
5. Dependency collection and analysis
158
6. Module wrapping or script handling
159
7. Code generation with source maps
160
8. Optional minification
161
162
#### JSON Files
163
164
JSON files are converted to CommonJS modules for seamless integration with JavaScript bundling.
165
166
```javascript { .api }
167
// Input file type for JSON processing
168
interface JSONFile {
169
filename: string;
170
inputFileSize: number;
171
code: string;
172
type: Type;
173
}
174
```
175
176
**Processing steps:**
177
1. JSON content validation
178
2. CommonJS module wrapper generation
179
3. Optional minification
180
4. Source map generation
181
182
#### Asset Files
183
184
Asset files (images, fonts, etc.) are converted to JavaScript modules that reference asset registry entries.
185
186
```javascript { .api }
187
// Input file type for asset processing
188
interface AssetFile {
189
filename: string;
190
inputFileSize: number;
191
code: string;
192
type: "asset";
193
}
194
```
195
196
**Processing steps:**
197
1. Asset metadata extraction (dimensions, file size, etc.)
198
2. Asset registry integration
199
3. JavaScript module AST generation
200
4. Standard JavaScript processing pipeline
201
202
### Transformation Response
203
204
```javascript { .api }
205
interface TransformResponse {
206
/** Array of module dependencies discovered during transformation */
207
dependencies: TransformResultDependency[];
208
/** Array of output chunks (JavaScript or Hermes bytecode) */
209
output: (JsOutput | BytecodeOutput)[];
210
}
211
212
interface JsOutput {
213
data: {
214
/** Transformed JavaScript code ready for bundling */
215
code: string;
216
/** Number of lines in the transformed code */
217
lineCount: number;
218
/** Source map segments for debugging */
219
map: MetroSourceMapSegmentTuple[];
220
/** Function map for advanced debugging (React Native) */
221
functionMap: FBSourceFunctionMap | null;
222
};
223
/** File type classification for bundler handling */
224
type: JSFileType;
225
}
226
227
interface BytecodeOutput {
228
/** Opaque bytecode data for Hermes runtime */
229
data: unknown;
230
/** Bytecode file type classification */
231
type: BytecodeFileType;
232
}
233
```
234
235
### Error Handling
236
237
The transformation pipeline provides detailed error reporting with file context:
238
239
```javascript { .api }
240
class InvalidRequireCallError extends Error {
241
/** Original error from dependency collection */
242
innerError: InternalInvalidRequireCallError;
243
/** File where the error occurred */
244
filename: string;
245
246
constructor(innerError: InternalInvalidRequireCallError, filename: string);
247
}
248
```
249
250
**Common error scenarios:**
251
- Invalid `require()` call syntax
252
- Malformed import/export statements
253
- Babel transformation failures
254
- Minification syntax errors
255
- Reserved string conflicts (e.g., Metro internal variables)
256
257
**Error context includes:**
258
- File path and line numbers
259
- Specific syntax issues
260
- Configuration that led to the error
261
- Suggestions for resolution