0
# Babel Processing Engine
1
2
Core Babel 7 processing functionality that performs the actual code transformation with comprehensive AST management, source mapping, and performance optimization.
3
4
## Capabilities
5
6
### Babel 7 Transformation
7
8
Main function that performs Babel transformation using @babel/core with full configuration and AST management.
9
10
```javascript { .api }
11
/**
12
* Performs Babel 7 transformation on JavaScript/TypeScript/JSX assets
13
* Handles AST processing, plugin configuration, and performance tracing
14
* Modifies the asset's AST in place rather than returning it
15
* @param opts - Transformation options
16
* @returns Promise that resolves when transformation is complete (returns undefined)
17
*/
18
async function babel7(opts: Babel7TransformOptions): Promise<void>;
19
20
interface Babel7TransformOptions {
21
asset: MutableAsset; // The asset being transformed
22
options: PluginOptions; // Parcel plugin options
23
logger: PluginLogger; // Logger for warnings and errors
24
babelOptions: any; // Babel configuration object
25
additionalPlugins?: Array<any>; // Extra plugins from asset metadata
26
tracer: PluginTracer; // Performance tracing utility
27
}
28
```
29
30
### Babel Configuration Assembly
31
32
The function assembles a comprehensive Babel configuration from multiple sources:
33
34
```javascript { .api }
35
// Configuration structure passed to @babel/core
36
interface BabelTransformConfig {
37
plugins: Array<any>; // Combined plugins array
38
presets: Array<any>; // Babel presets
39
code: false; // Disable code generation
40
ast: true; // Enable AST output
41
filename: string; // Source file path
42
babelrc: false; // Disable .babelrc loading
43
configFile: false; // Disable babel.config.* loading
44
parserOpts: ParserOptions; // Parser configuration
45
caller: CallerOptions; // Caller identification
46
wrapPluginVisitorMethod?: Function; // Performance tracing wrapper
47
}
48
49
interface ParserOptions {
50
sourceFilename: string; // Relative source filename
51
allowReturnOutsideFunction: true; // Allow top-level returns
52
strictMode: false; // Disable strict mode enforcement
53
sourceType: 'module'; // Always treat as ES module
54
plugins: Array<string>; // Syntax plugins to enable
55
}
56
57
interface CallerOptions {
58
name: 'parcel'; // Identifies Parcel as caller
59
version: string; // Transformer version
60
targets: string; // JSON stringified targets
61
outputFormat: string; // Output format (esm, cjs, etc.)
62
}
63
```
64
65
### AST Processing Modes
66
67
The function handles two different processing modes based on asset state:
68
69
```javascript { .api }
70
// Mode 1: Transform from existing AST
71
const result = await babelCore.transformFromAstAsync(
72
ast.program, // Existing AST program
73
asset.isASTDirty() ? undefined : await asset.getCode(), // Code if AST is clean
74
config // Babel configuration
75
);
76
77
// Mode 2: Transform from source code
78
const result = await babelCore.transformAsync(
79
await asset.getCode(), // Source code string
80
config // Babel configuration
81
);
82
```
83
84
### Source Map Remapping
85
86
When transforming from source code, the function remaps AST locations using existing source maps:
87
88
```javascript { .api }
89
/**
90
* Remaps AST node locations using source map for accurate debugging
91
* Applied when transforming from source code rather than existing AST
92
*/
93
if (res.ast && !ast) {
94
let map = await asset.getMap();
95
if (map) {
96
remapAstLocations(babelCore.types, res.ast, map);
97
}
98
}
99
```
100
101
### External Dependencies Handling
102
103
Processes external dependencies declared by Babel plugins:
104
105
```javascript { .api }
106
// External dependency processing
107
if (res.externalDependencies) {
108
for (let filePath of res.externalDependencies) {
109
if (!path.isAbsolute(filePath)) {
110
// Warn about non-absolute dependencies
111
logger.warn({
112
message: `Ignoring non-absolute Babel external dependency: ${filePath}`,
113
hints: ['Please report this to the corresponding Babel plugin and/or to Parcel.']
114
});
115
} else {
116
// Track file changes/creation for cache invalidation
117
if (await options.inputFS.exists(filePath)) {
118
asset.invalidateOnFileChange(filePath);
119
} else {
120
asset.invalidateOnFileCreate({ filePath });
121
}
122
}
123
}
124
}
125
```
126
127
### Performance Tracing
128
129
Integrates with Parcel's performance tracing system to monitor plugin execution:
130
131
```javascript { .api }
132
/**
133
* Wraps Babel plugin visitor methods for performance measurement
134
* Only active when tracer.enabled is true
135
*/
136
config.wrapPluginVisitorMethod = (
137
key: string, // Plugin identifier
138
nodeType: string, // AST node type being visited
139
fn: Function // Original visitor function
140
) => {
141
return function() {
142
const measurement = tracer.createMeasurement(
143
key.startsWith(options.projectRoot)
144
? path.relative(options.projectRoot, key)
145
: key,
146
nodeType,
147
path.relative(options.projectRoot, asset.filePath)
148
);
149
150
fn.apply(this, arguments);
151
measurement && measurement.end();
152
};
153
};
154
```
155
156
### Syntax Plugin Configuration
157
158
Automatically configures essential syntax plugins for modern JavaScript:
159
160
```javascript { .api }
161
const defaultSyntaxPlugins = [
162
'classProperties', // class field declarations
163
'classPrivateProperties', // private class fields
164
'classPrivateMethods', // private class methods
165
'exportDefaultFrom' // export { default } from 'module'
166
// 'topLevelAwait' - commented out, conditionally enabled
167
];
168
169
// Combined with config-specific syntax plugins
170
const allSyntaxPlugins = [
171
...(babelOptions.config.parserOpts?.plugins ?? []),
172
...(babelOptions.syntaxPlugins ?? []),
173
...defaultSyntaxPlugins
174
];
175
```
176
177
### AST Output Handling
178
179
Sets the transformed AST on the asset with proper metadata:
180
181
```javascript { .api }
182
/**
183
* Sets the transformed AST on the asset
184
* Includes version information for AST reuse optimization
185
*/
186
if (res.ast) {
187
asset.setAST({
188
type: 'babel', // AST type identifier
189
version: '7.0.0', // Babel version for compatibility
190
program: res.ast // Transformed AST program
191
});
192
}
193
```
194
195
**Usage Example:**
196
197
```javascript
198
// Internal usage during transformation
199
const transformedAST = await babel7({
200
asset: jsAsset,
201
options: pluginOptions,
202
logger: parcelLogger,
203
babelOptions: {
204
config: {
205
presets: [['@babel/preset-env', { targets: { node: '16' } }]],
206
plugins: ['@babel/plugin-proposal-class-properties']
207
},
208
targets: { node: '16.0.0' },
209
syntaxPlugins: ['jsx']
210
},
211
additionalPlugins: [],
212
tracer: performanceTracer
213
});
214
215
// AST is set on the asset and returned for further processing
216
console.log('Transformation complete:', transformedAST !== null);
217
```
218
219
## Dependency Management
220
221
The function handles automatic installation and resolution of Babel dependencies:
222
223
- **@babel/core**: Required with version ^7.12.0
224
- **@babel/generator**: Loaded dynamically for code generation
225
- **Plugin Dependencies**: Resolved and cached automatically
226
- **Version Validation**: Ensures compatible versions across the pipeline
227
228
## Error Handling
229
230
- **Transformation Errors**: Full context with source location
231
- **Dependency Errors**: Clear messages for missing or incompatible packages
232
- **Configuration Errors**: Detailed information about invalid settings
233
- **AST Errors**: Validation of AST structure and compatibility
234
235
## Performance Optimizations
236
237
- **AST Reuse**: Avoids re-parsing when compatible AST exists
238
- **Lazy Loading**: Dependencies loaded only when needed
239
- **Source Map Optimization**: Efficient location remapping
240
- **Plugin Tracing**: Optional performance monitoring
241
- **Cache Integration**: Leverages Parcel's caching system