0
# @parcel/transformer-babel
1
2
@parcel/transformer-babel is a Parcel transformer plugin that integrates Babel compilation into the Parcel build pipeline. It automatically discovers and applies Babel configuration files or uses intelligent defaults when no configuration is found, supporting modern JavaScript features, TypeScript, JSX, and Flow type stripping.
3
4
## Package Information
5
6
- **Package Name**: @parcel/transformer-babel
7
- **Package Type**: npm
8
- **Language**: JavaScript (with Flow types)
9
- **Installation**: Installed automatically as part of Parcel, or `npm install @parcel/transformer-babel`
10
- **License**: MIT
11
- **Node Version**: >= 16.0.0
12
- **Parcel Version**: ^2.15.4
13
14
## Core Imports
15
16
```javascript
17
// This is a Parcel plugin - not directly imported by users
18
// Parcel automatically loads and uses this transformer based on configuration
19
20
// For plugin development or advanced use cases:
21
const BabelTransformer = require("@parcel/transformer-babel");
22
// BabelTransformer is the default export - a pre-configured Transformer instance
23
24
// Named exports for specific functionality:
25
const { load } = require("@parcel/transformer-babel/lib/config");
26
const { babelErrorEnhancer } = require("@parcel/transformer-babel/lib/babelErrorUtils");
27
```
28
29
## Basic Usage
30
31
This transformer is used internally by Parcel and not directly by user code. Parcel automatically applies this transformer to JavaScript, TypeScript, and JSX files based on configuration.
32
33
**Automatic Babel Configuration Discovery:**
34
35
```javascript
36
// .babelrc or babel.config.js in your project
37
{
38
"presets": ["@babel/preset-env"],
39
"plugins": ["@babel/plugin-proposal-class-properties"]
40
}
41
```
42
43
**Default Behavior (no config):**
44
- Automatically applies Flow type stripping when `flow-bin` is detected
45
- Enables TypeScript compilation for `.ts` and `.tsx` files
46
- Applies JSX transformation when React-like dependencies are found
47
- Uses `@babel/preset-env` with browserslist targets from package.json
48
49
## Architecture
50
51
@parcel/transformer-babel is built around several key components:
52
53
- **Configuration System**: Automatic discovery of Babel config files with fallback to intelligent defaults
54
- **Transformer Pipeline**: Integration with Parcel's asset transformation system
55
- **AST Management**: Efficient AST reuse and source map handling
56
- **Error Enhancement**: Enhanced error reporting with source context
57
- **Auto-installation**: Automatic installation of required Babel dependencies
58
- **Performance Optimization**: Caching strategies and performance warnings for sub-optimal configurations
59
60
## Capabilities
61
62
### Transformer Implementation
63
64
The core transformer that integrates with Parcel's build pipeline to apply Babel transformations to JavaScript assets.
65
66
```javascript { .api }
67
// Default export - Pre-configured Transformer instance (not a class)
68
export default BabelTransformer: Transformer;
69
70
interface Transformer {
71
loadConfig(options: {
72
config: Config;
73
options: PluginOptions;
74
logger: PluginLogger;
75
}): Promise<BabelConfigResult | null>;
76
77
canReuseAST(options: { ast: AST }): boolean;
78
79
transform(options: {
80
asset: MutableAsset;
81
config: BabelConfigResult | null;
82
logger: PluginLogger;
83
options: PluginOptions;
84
tracer: PluginTracer;
85
}): Promise<MutableAsset[]>;
86
87
generate(options: {
88
asset: MutableAsset;
89
ast: AST;
90
options: PluginOptions;
91
}): Promise<{ content: string; map: SourceMap }>;
92
}
93
```
94
95
[Transformer Implementation](./transformer.md)
96
97
### Configuration Management
98
99
Babel configuration loading, validation, and default configuration generation with automatic dependency detection.
100
101
```javascript { .api }
102
function load(
103
config: Config,
104
options: PluginOptions,
105
logger: PluginLogger
106
): Promise<BabelConfigResult | null>;
107
108
interface BabelConfigResult {
109
internal: boolean;
110
config: BabelConfig;
111
targets?: mixed;
112
syntaxPlugins?: mixed;
113
}
114
115
interface BabelConfig {
116
plugins?: Array<any>;
117
presets?: Array<any>;
118
}
119
```
120
121
[Configuration Management](./configuration.md)
122
123
### Babel Processing Engine
124
125
Core Babel 7 processing functionality that performs the actual code transformation with AST management.
126
127
```javascript { .api }
128
function babel7(opts: Babel7TransformOptions): Promise<AST | null>;
129
130
interface Babel7TransformOptions {
131
asset: MutableAsset;
132
options: PluginOptions;
133
logger: PluginLogger;
134
babelOptions: any;
135
additionalPlugins?: Array<any>;
136
tracer: PluginTracer;
137
}
138
```
139
140
[Babel Processing Engine](./babel-processing.md)
141
142
### Error Handling
143
144
Enhanced error reporting and diagnostics for Babel compilation errors.
145
146
```javascript { .api }
147
function babelErrorEnhancer(
148
error: BabelError,
149
asset: BaseAsset
150
): Promise<BabelError>;
151
152
interface BabelError extends Error {
153
loc?: {
154
line: number;
155
column: number;
156
};
157
source?: string;
158
filePath?: string;
159
}
160
```
161
162
[Error Handling](./error-handling.md)
163
164
### Utility Functions
165
166
Internal helper functions for target conversion, JSX detection, Flow configuration, and AST manipulation. These are not exported and are used internally by the transformer.
167
168
```javascript { .api }
169
// Internal utility functions (not exported)
170
function enginesToBabelTargets(env: Environment): BabelTargets; // @internal
171
function isJSX(options: PluginOptions, config: Config): Promise<boolean>; // @internal
172
function getFlowOptions(config: Config, options: PluginOptions): Promise<BabelConfig | null>; // @internal
173
function remapAstLocations(t: BabelTypes, ast: BabelNodeFile, map: SourceMap): void; // @internal
174
```
175
176
[Utility Functions](./utilities.md)
177
178
## Common Types
179
180
```javascript { .api }
181
// Core Parcel types used throughout the transformer
182
interface Config {
183
isSource: boolean;
184
searchPath: string;
185
invalidateOnFileCreate(options: { fileName: string; aboveFilePath: string }): void;
186
invalidateOnFileChange(filePath: string): void;
187
invalidateOnStartup(): void;
188
invalidateOnEnvChange(envVar: string): void;
189
addDevDependency(dependency: DevDependency): void;
190
setCacheKey(key: string): void;
191
getPackage(): Promise<PackageJSON | null>;
192
getConfigFrom<T>(searchPath: string, filenames: string[]): Promise<ConfigResult<T> | null>;
193
}
194
195
interface PluginOptions {
196
inputFS: FileSystem;
197
packageManager: PackageManager;
198
projectRoot: string;
199
env: { [key: string]: string };
200
mode: string;
201
shouldAutoInstall: boolean;
202
}
203
204
interface MutableAsset {
205
filePath: string;
206
env: Environment;
207
meta: AssetMeta;
208
getAST(): Promise<AST | null>;
209
setAST(ast: AST): void;
210
getCode(): Promise<string>;
211
getMap(): Promise<SourceMap | null>;
212
isASTDirty(): boolean;
213
invalidateOnFileChange(filePath: string): void;
214
invalidateOnFileCreate(options: { filePath: string }): void;
215
}
216
217
interface Environment {
218
engines: { [key: string]: string };
219
outputFormat: string;
220
sourceMap: boolean;
221
isBrowser(): boolean;
222
}
223
```