0
# Utility Functions
1
2
Internal helper functions for target conversion, JSX detection, Flow configuration, and AST manipulation that support the core Babel transformation functionality. These functions are not directly exported but are used internally by the transformer.
3
4
## Capabilities
5
6
### Target Conversion
7
8
Converts Parcel's engine specifications to Babel preset-env targets format.
9
10
```javascript { .api }
11
/**
12
* Converts Parcel's engine specifications to Babel preset-env targets
13
* Handles browser targets, Node.js versions, and ES module output optimization
14
* @param env - Parcel environment object with engine specifications
15
* @returns BabelTargets object compatible with @babel/preset-env
16
* @internal - Used internally by the configuration system
17
*/
18
function enginesToBabelTargets(env: Environment): BabelTargets;
19
20
interface Environment {
21
engines: { [engineName: string]: string }; // Engine version specifications
22
outputFormat: string; // Output format (esm, cjs, etc.)
23
isBrowser(): boolean; // Browser environment check
24
}
25
26
interface BabelTargets {
27
[engineName: string]: string | boolean | Array<string>;
28
browsers?: string | Array<string>; // Browser target queries
29
esmodules?: boolean; // ES modules target flag
30
}
31
```
32
33
**Supported Target Names:**
34
```javascript { .api }
35
const TargetNames = {
36
node: 'node',
37
chrome: 'chrome',
38
opera: 'opera',
39
edge: 'edge',
40
firefox: 'firefox',
41
safari: 'safari',
42
ie: 'ie',
43
ios: 'ios',
44
android: 'android',
45
electron: 'electron',
46
samsung: 'samsung',
47
rhino: 'rhino'
48
};
49
```
50
51
**ES Module Browser Exclusions:**
52
```javascript { .api }
53
const ESMODULE_BROWSERS = [
54
'not ie <= 11',
55
'not edge < 16',
56
'not firefox < 60',
57
'not chrome < 61',
58
'not safari < 11',
59
'not opera < 48',
60
'not ios_saf < 11',
61
'not op_mini all',
62
'not android < 76',
63
'not blackberry > 0',
64
'not op_mob > 0',
65
'not and_chr < 76',
66
'not and_ff < 68',
67
'not ie_mob > 0',
68
'not and_uc > 0',
69
'not samsung < 8.2',
70
'not and_qq > 0',
71
'not baidu > 0',
72
'not kaios > 0'
73
];
74
```
75
76
**Usage Examples:**
77
78
```javascript
79
// Convert Parcel engines to Babel targets
80
const env = {
81
engines: {
82
node: '>=16.0.0',
83
browsers: ['> 1%', 'last 2 versions']
84
},
85
outputFormat: 'cjs',
86
isBrowser: () => false
87
};
88
89
const targets = enginesToBabelTargets(env);
90
// Result: { node: '16.0.0', browsers: ['> 1%', 'last 2 versions'] }
91
92
// ES module output with browser targets
93
const esmEnv = {
94
engines: { browsers: '> 1%' },
95
outputFormat: 'esmodule',
96
isBrowser: () => true
97
};
98
99
const esmTargets = enginesToBabelTargets(esmEnv);
100
// Result: { browsers: ['> 1%', 'not ie <= 11', 'not edge < 16', ...] }
101
```
102
103
### JSX Detection
104
105
Determines if a file likely contains JSX syntax based on file extension and project dependencies.
106
107
```javascript { .api }
108
/**
109
* Detects if an asset likely contains JSX syntax
110
* Checks file extensions and React-like dependencies in package.json
111
* @param options - Plugin options for dependency resolution
112
* @param config - Parcel configuration object
113
* @returns Promise resolving to true if JSX is likely present
114
* @internal - Used internally by the configuration system
115
*/
116
async function isJSX(
117
options: PluginOptions,
118
config: Config
119
): Promise<boolean>;
120
```
121
122
**JSX Detection Logic:**
123
124
1. **Non-Source Files**: Returns false for node_modules files
125
2. **File Extension Check**: Automatically true for `.jsx` and `.tsx` files
126
3. **React Alias Check**: Detects React aliases in package.json
127
4. **Dependency Check**: Searches for React-like libraries in dependencies
128
129
**Supported Extensions:**
130
```javascript { .api }
131
const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']);
132
```
133
134
**Detected Libraries:**
135
```javascript { .api }
136
const JSX_LIBRARIES = ['react', 'preact', 'nervejs', 'hyperapp'];
137
```
138
139
**Usage Examples:**
140
141
```javascript
142
// Check if file contains JSX
143
const hasJSX = await isJSX(pluginOptions, parcelConfig);
144
145
// File extension detection
146
// Button.jsx -> true
147
// Component.tsx -> true
148
// utils.js -> depends on dependencies
149
150
// Dependency detection
151
// package.json with "react": "^18.0.0" -> true for .js files
152
// package.json with "preact": "^10.0.0" -> true for .js files
153
// No React-like deps -> false for .js files
154
155
// Alias detection
156
// package.json: { "alias": { "react": "preact/compat" } } -> true
157
```
158
159
### Flow Configuration
160
161
Generates Babel configuration for stripping Flow type annotations when Flow is detected in the project.
162
163
```javascript { .api }
164
/**
165
* Generates Babel configuration for Flow type stripping
166
* Only applies when flow-bin is detected as a project dependency
167
* @param config - Parcel configuration object
168
* @param options - Plugin options for dependency resolution
169
* @returns Promise resolving to BabelConfig for Flow or null if not needed
170
* @internal - Used internally by the configuration system
171
*/
172
async function getFlowOptions(
173
config: Config,
174
options: PluginOptions
175
): Promise<BabelConfig | null>;
176
177
interface BabelConfig {
178
plugins?: Array<any>;
179
presets?: Array<any>;
180
}
181
```
182
183
**Flow Detection Process:**
184
185
1. **Non-Source Files**: Returns null for node_modules files
186
2. **Test Environment Exception**: Special handling for @parcel/error-overlay in tests
187
3. **Dependency Check**: Searches for `flow-bin` in dependencies or devDependencies
188
4. **Plugin Configuration**: Creates Flow strip types plugin configuration
189
5. **Dependency Installation**: Ensures required Babel plugins are available
190
191
**Usage Examples:**
192
193
```javascript
194
// Generate Flow configuration
195
const flowConfig = await getFlowOptions(parcelConfig, pluginOptions);
196
197
// With flow-bin dependency:
198
// {
199
// plugins: [
200
// ['@babel/plugin-transform-flow-strip-types', { requireDirective: true }]
201
// ]
202
// }
203
204
// Without flow-bin dependency:
205
// null
206
207
// Example Flow code transformation:
208
// Input: function add(a: number, b: number): number { return a + b; }
209
// Output: function add(a, b) { return a + b; }
210
```
211
212
### AST Location Remapping
213
214
Remaps AST node locations using source maps for accurate debugging information.
215
216
```javascript { .api }
217
/**
218
* Remaps AST node locations using source map for accurate sourcemap generation
219
* Improves sourcemap accuracy and fixes sourcemaps when scope-hoisting
220
* @param t - Babel types utility object
221
* @param ast - Babel AST file node
222
* @param map - Source map for location mapping
223
* @internal - Used internally by the Babel processing engine
224
*/
225
function remapAstLocations(
226
t: BabelTypes,
227
ast: BabelNodeFile,
228
map: SourceMap
229
): void;
230
231
interface BabelNodeFile {
232
program: any; // AST program node
233
}
234
235
interface SourceMap {
236
findClosestMapping(line: number, column: number): Mapping | null;
237
}
238
239
interface Mapping {
240
original: {
241
line: number; // Original source line
242
column: number; // Original source column
243
};
244
source: string; // Original source file name
245
}
246
```
247
248
**Remapping Process:**
249
250
1. **AST Traversal**: Visits all nodes in the AST recursively
251
2. **Location Check**: Processes nodes with location information
252
3. **Mapping Lookup**: Finds closest source map mapping for each location
253
4. **Location Update**: Updates start and end positions with original coordinates
254
5. **Filename Update**: Sets original source filename on nodes
255
6. **Null Mapping Handling**: Removes location for unmappable positions
256
257
**Usage Examples:**
258
259
```javascript
260
// Remap AST locations after transformation
261
const sourceMap = await asset.getMap();
262
if (sourceMap && transformedAST) {
263
remapAstLocations(babelTypes, transformedAST, sourceMap);
264
}
265
266
// Before remapping (compiled locations):
267
// Node at line 10, column 5 in compiled output
268
269
// After remapping (original locations):
270
// Node at line 8, column 2 in original source
271
// Filename: 'src/components/Button.jsx'
272
```
273
274
### Internal Tree Traversal
275
276
Helper function for traversing all nodes in an AST tree.
277
278
```javascript { .api }
279
/**
280
* Recursively traverses all nodes in an AST tree
281
* Used internally by remapAstLocations for complete tree processing
282
* @param t - Babel types utility object
283
* @param node - Current AST node to traverse
284
* @param visitor - Visitor function called for each node
285
*/
286
function traverseAll(
287
t: BabelTypes,
288
node: Node,
289
visitor: (node: Node) => void
290
): void;
291
```
292
293
**Traversal Features:**
294
- **Recursive Processing**: Handles nested node structures
295
- **Visitor Pattern**: Calls visitor function for each node
296
- **Type-Aware**: Uses Babel's VISITOR_KEYS for proper traversal
297
- **Array Handling**: Processes arrays of nodes correctly
298
- **Null Safety**: Handles null/undefined nodes gracefully
299
300
## Constants and Configuration
301
302
### Version Requirements
303
304
```javascript { .api }
305
const BABEL_CORE_RANGE = '^7.12.0'; // Required @babel/core version
306
```
307
308
### File Extensions
309
310
```javascript { .api }
311
const TYPESCRIPT_EXTNAME_RE = /\.tsx?$/; // TypeScript file detection
312
const JS_EXTNAME_RE = /^\.(js|cjs|mjs)$/; // JavaScript file detection
313
```
314
315
## Error Handling
316
317
All utility functions include appropriate error handling:
318
319
- **Dependency Resolution**: Graceful handling of missing dependencies
320
- **File System Access**: Safe file reading with fallbacks
321
- **Version Compatibility**: Validation of Babel version requirements
322
- **Configuration Validation**: Proper handling of invalid configurations
323
324
## Performance Considerations
325
326
- **Lazy Loading**: Dependencies loaded only when needed
327
- **Caching**: Results cached where appropriate
328
- **Efficient Traversal**: Optimized AST traversal algorithms
329
- **Minimal Processing**: Only processes when transformations are needed