0
# Parcel JavaScript Transformer
1
2
@parcel/transformer-js is a JavaScript and TypeScript transformer plugin for the Parcel bundler. It provides comprehensive JavaScript compilation, transformation, and optimization capabilities including JSX support, TypeScript compilation, React Fast Refresh, and environment-specific transformations.
3
4
## Package Information
5
6
- **Package Name**: @parcel/transformer-js
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install @parcel/transformer-js`
10
11
## Core Imports
12
13
The transformer is typically used as a Parcel plugin and not imported directly. However, internal utilities are available:
14
15
```javascript
16
// Main transformer (for plugin development) - ES module default export
17
import JSTransformer from "@parcel/transformer-js";
18
19
// ESModule helpers (internal runtime support) - CommonJS exports
20
const { interopDefault, defineInteropFlag, exportAll, export } = require("@parcel/transformer-js/src/esmodule-helpers");
21
22
// MDX components (for MDX transformation) - ES module export
23
import { useMDXComponents } from "@parcel/transformer-js/src/mdx-components.jsx";
24
```
25
26
For plugin registration (Parcel configuration):
27
28
```javascript
29
// .parcelrc
30
{
31
"transformers": {
32
"*.{js,mjs,jsx,cjs,ts,tsx}": ["@parcel/transformer-js"]
33
}
34
}
35
```
36
37
## Basic Usage
38
39
This transformer is automatically used by Parcel for JavaScript and TypeScript files. Configuration is typically done through:
40
41
```javascript
42
// tsconfig.json
43
{
44
"compilerOptions": {
45
"jsx": "react-jsx",
46
"jsxImportSource": "react",
47
"experimentalDecorators": true,
48
"useDefineForClassFields": true,
49
"target": "es2022"
50
}
51
}
52
```
53
54
Package-level configuration:
55
56
```json
57
// package.json
58
{
59
"@parcel/transformer-js": {
60
"inlineFS": false,
61
"inlineEnvironment": ["NODE_ENV", "DEBUG"],
62
"unstable_inlineConstants": true
63
}
64
}
65
```
66
67
## Architecture
68
69
The transformer is built on several key components:
70
71
- **Parcel Plugin Interface**: Implements Parcel's Transformer interface with `loadConfig` and `transform` methods
72
- **Rust Core**: Performance-critical transformations implemented in Rust for speed
73
- **Configuration System**: Automatic detection of JSX libraries, TypeScript settings, and build targets
74
- **Runtime Helpers**: ES module interoperability functions for generated code
75
- **Environment Targeting**: Browser compatibility, Node.js, and Electron targeting via browserslist
76
77
## Capabilities
78
79
### JavaScript/TypeScript Transformation
80
81
Core transformation functionality for modern JavaScript and TypeScript files with automatic configuration detection.
82
83
```javascript { .api }
84
/**
85
* Main transformer instance - implements Parcel's Transformer interface
86
* Supports: JS, JSX, TS, TSX, MDX files
87
* Default export is a configured Transformer instance
88
*/
89
const JSTransformer: Transformer;
90
export default JSTransformer;
91
92
interface TransformerConfig {
93
isJSX?: boolean;
94
automaticJSXRuntime?: boolean;
95
jsxImportSource?: string;
96
pragma?: string;
97
pragmaFrag?: string;
98
inlineEnvironment?: boolean | string[];
99
inlineFS?: boolean;
100
inlineConstants?: boolean;
101
reactRefresh?: boolean;
102
decorators?: boolean;
103
useDefineForClassFields?: boolean;
104
}
105
```
106
107
### ESModule Runtime Helpers
108
109
Utility functions for ES module interoperability in generated code.
110
111
```javascript { .api }
112
/**
113
* Provides default export interop for CommonJS modules
114
* Returns the module as-is if it has __esModule, otherwise wraps it with {default: module}
115
* @param a - Module to provide interop for
116
* @returns Module with default property if needed
117
*/
118
function interopDefault(a: any): any;
119
120
/**
121
* Defines __esModule property on exports object using Object.defineProperty
122
* @param a - Exports object to mark as ES module
123
*/
124
function defineInteropFlag(a: object): void;
125
126
/**
127
* Copies all enumerable properties from source to dest using getters
128
* Excludes 'default', '__esModule', and existing properties in dest
129
* @param source - Source object to copy from
130
* @param dest - Destination object to copy to
131
* @returns Destination object
132
*/
133
function exportAll(source: object, dest: object): object;
134
135
/**
136
* Defines a single named export with getter using Object.defineProperty
137
* @param dest - Destination object
138
* @param destName - Property name to define
139
* @param get - Getter function for the property
140
*/
141
function export(dest: object, destName: string, get: () => any): void;
142
```
143
144
### MDX Component Support
145
146
Default components for MDX file transformation.
147
148
```jsx { .api }
149
/**
150
* Returns default MDX component mappings
151
* @returns Object containing default components (currently includes CodeBlock)
152
*/
153
function useMDXComponents(): {
154
CodeBlock: React.ComponentType<CodeBlockProps>;
155
};
156
157
/**
158
* Default code block component for MDX rendering
159
* Renders a <pre><code> block with optional language class and additional render content
160
*/
161
interface CodeBlockProps {
162
lang?: string;
163
children: React.ReactNode;
164
render?: React.ReactNode;
165
}
166
167
/**
168
* CodeBlock component implementation
169
* Renders code within pre/code tags with language-specific CSS class
170
*/
171
const CodeBlock: React.ComponentType<CodeBlockProps>;
172
```
173
174
### Configuration Schema
175
176
JSON schema for package-level transformer configuration.
177
178
```typescript { .api }
179
interface ConfigOptions {
180
/**
181
* Whether to inline filesystem calls (default: true unless browser.fs = false)
182
*/
183
inlineFS?: boolean;
184
185
/**
186
* Environment variable inlining configuration
187
* - boolean: inline all (true) or only NODE_ENV (false)
188
* - string[]: glob patterns for environment variables to inline
189
*/
190
inlineEnvironment?: boolean | string[];
191
192
/**
193
* Whether to inline constants (experimental feature)
194
*/
195
unstable_inlineConstants?: boolean;
196
}
197
198
// JSON schema definition used internally for validation
199
const CONFIG_SCHEMA: {
200
type: 'object';
201
properties: {
202
inlineFS: { type: 'boolean' };
203
inlineEnvironment: {
204
oneOf: [
205
{ type: 'boolean' };
206
{ type: 'array'; items: { type: 'string' } };
207
];
208
};
209
unstable_inlineConstants: { type: 'boolean' };
210
};
211
additionalProperties: false;
212
};
213
```
214
215
### JSX and TypeScript Support
216
217
Automatic configuration for JSX and TypeScript based on dependencies and tsconfig.json.
218
219
**Supported JSX Libraries:**
220
221
```typescript { .api }
222
// JSX pragma configurations for different libraries
223
interface JSXPragmaConfig {
224
pragma: string;
225
pragmaFrag?: string;
226
automatic?: string; // Version range for automatic JSX runtime
227
}
228
229
const JSX_PRAGMA: {
230
react: {
231
pragma: 'React.createElement';
232
pragmaFrag: 'React.Fragment';
233
automatic: '>= 17.0.0 || ^16.14.0 || >= 0.0.0-0 < 0.0.0';
234
};
235
preact: {
236
pragma: 'h';
237
pragmaFrag: 'Fragment';
238
automatic: '>= 10.5.0';
239
};
240
nervjs: {
241
pragma: 'Nerv.createElement';
242
pragmaFrag: undefined;
243
automatic: undefined;
244
};
245
hyperapp: {
246
pragma: 'h';
247
pragmaFrag: undefined;
248
automatic: undefined;
249
};
250
};
251
```
252
253
- React (with automatic JSX runtime detection for React 17+)
254
- Preact
255
- Nerv
256
- Hyperapp
257
258
**TypeScript Compiler Options:**
259
260
```typescript { .api }
261
interface TSConfig {
262
compilerOptions?: {
263
jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native';
264
jsxFactory?: string;
265
jsxFragmentFactory?: string;
266
jsxImportSource?: string;
267
experimentalDecorators?: boolean;
268
useDefineForClassFields?: boolean;
269
target?: string;
270
};
271
}
272
```
273
274
### Environment Targeting
275
276
Automatic browser and runtime targeting based on configuration.
277
278
**Supported Targets:**
279
280
```typescript { .api }
281
// Browser name mapping for target compilation
282
const BROWSER_MAPPING: Record<string, string | null>;
283
284
// Browser exclusion rules for ES module targeting
285
const ESMODULE_BROWSERS: string[];
286
```
287
288
- Browser compatibility via browserslist
289
- Node.js version targeting
290
- Electron application support
291
- ES module vs. script targeting
292
- Web Workers and Service Workers
293
- Worklets
294
295
**Target Detection:**
296
- `package.json` browserslist field
297
- `.browserslistrc` file
298
- `engines.node` for Node.js targeting
299
- `engines.electron` for Electron apps
300
301
### Development Features
302
303
Development-specific functionality for enhanced developer experience.
304
305
**Features:**
306
307
```typescript { .api }
308
// Macro context for compile-time code generation
309
interface MacroAsset {
310
type: string;
311
content: string;
312
}
313
314
interface MacroContext {
315
addAsset(asset: MacroAsset): void;
316
loc: SourceLocation;
317
invalidateOnFileChange(path: string): void;
318
invalidateOnFileCreate(invalidation: FileCreateInvalidation): void;
319
invalidateOnEnvChange(env: string): void;
320
invalidateOnStartup(): void;
321
invalidateOnBuild(): void;
322
}
323
```
324
325
- React Fast Refresh integration
326
- Hot module replacement support
327
- Source map generation and preservation
328
- Diagnostic error reporting with hints
329
- Macro system for compile-time code generation
330
331
### Build Optimizations
332
333
Production build optimizations applied automatically.
334
335
**Optimizations:**
336
337
```typescript { .api }
338
// File extensions that enable JSX parsing
339
const JSX_EXTENSIONS: {
340
jsx: true;
341
tsx: true;
342
};
343
344
// Browser name mapping for target compilation
345
const BROWSER_MAPPING: {
346
and_chr: 'chrome';
347
and_ff: 'firefox';
348
ie_mob: 'ie';
349
ios_saf: 'ios';
350
op_mob: 'opera';
351
and_qq: null;
352
and_uc: null;
353
baidu: null;
354
bb: null;
355
kaios: null;
356
op_mini: null;
357
};
358
359
// Browser exclusion rules for ES module targeting
360
const ESMODULE_BROWSERS: string[];
361
```
362
363
- Tree shaking preparation
364
- Constant folding and inlining
365
- Environment variable replacement
366
- Dead code elimination
367
- Scope hoisting compatibility
368
- Bundle splitting support
369
370
## Error Handling
371
372
The transformer provides context-specific error messages for different execution environments:
373
374
```typescript { .api }
375
interface ScriptError {
376
message: string;
377
hint: string;
378
}
379
380
// Environment-specific errors for imports/exports in wrong contexts
381
const SCRIPT_ERRORS: {
382
browser: ScriptError;
383
'web-worker': ScriptError;
384
'service-worker': ScriptError;
385
}
386
```
387
388
389
## Required Type Definitions
390
391
```typescript { .api }
392
// Core Parcel types referenced in APIs
393
interface SourceLocation {
394
filePath: string;
395
start: {
396
line: number;
397
column: number;
398
};
399
end: {
400
line: number;
401
column: number;
402
};
403
}
404
405
interface FileCreateInvalidation {
406
glob: string;
407
}
408
409
// TypeScript compiler configuration interface
410
interface TSConfig {
411
compilerOptions?: {
412
jsx?: 'react' | 'react-jsx' | 'react-jsxdev' | 'preserve' | 'react-native';
413
jsxFactory?: string;
414
jsxFragmentFactory?: string;
415
jsxImportSource?: string;
416
experimentalDecorators?: boolean;
417
useDefineForClassFields?: boolean;
418
target?: string;
419
};
420
}
421
422
// Macro context interface for compile-time code generation
423
interface MacroContext {
424
addAsset(asset: MacroAsset): void;
425
loc: SourceLocation;
426
invalidateOnFileChange(filePath: string): void;
427
invalidateOnFileCreate(invalidation: FileCreateInvalidation): void;
428
invalidateOnEnvChange(env: string): void;
429
invalidateOnStartup(): void;
430
invalidateOnBuild(): void;
431
}
432
433
interface MacroAsset {
434
type: string;
435
content: string;
436
}
437
438
interface Asset {
439
// Parcel Asset interface details
440
}
441
442
interface Transformer {
443
// Parcel Transformer interface details
444
}
445
```
446
447
## Integration Notes
448
449
This transformer integrates deeply with the Parcel ecosystem:
450
451
- **@parcel/plugin**: Base transformer interface
452
- **@parcel/rust**: Rust transformation bindings for performance
453
- **@parcel/diagnostic**: Structured error reporting
454
- **@parcel/source-map**: Source map handling and composition
455
- **@parcel/utils**: Common utilities and validation
456
- **@parcel/workers**: Multi-threaded transformation processing
457
458
External dependencies include browserslist for browser targeting, semver for version comparisons, and various runtime helpers for generated code compatibility.