0
# Core Transformation
1
2
The core transformation system provides fast, focused compilation of modern JavaScript syntax extensions. All transformation is performed through the main `transform` function with extensive configuration options.
3
4
## Capabilities
5
6
### Transform Function
7
8
Primary transformation function that converts source code using specified transforms.
9
10
```typescript { .api }
11
/**
12
* Transform source code using specified transforms
13
* @param code - Source code string to transform
14
* @param options - Transform configuration options
15
* @returns Transform result with converted code and optional source map
16
*/
17
function transform(code: string, options: Options): TransformResult;
18
19
interface TransformResult {
20
code: string;
21
sourceMap?: RawSourceMap;
22
}
23
24
interface RawSourceMap {
25
version: number;
26
sources: string[];
27
names: string[];
28
mappings: string;
29
file?: string;
30
sourceRoot?: string;
31
sourcesContent?: (string | null)[];
32
}
33
```
34
35
**Usage Example:**
36
37
```typescript
38
import { transform } from "sucrase";
39
40
// Basic TypeScript transformation
41
const result = transform(
42
`function greet(name: string): string { return \`Hello, \${name}!\`; }`,
43
{ transforms: ["typescript"] }
44
);
45
46
// JSX with TypeScript and source maps
47
const jsxResult = transform(
48
`const Component: React.FC = () => <div>Hello</div>;`,
49
{
50
transforms: ["typescript", "jsx"],
51
sourceMapOptions: { compiledFilename: "Component.js" },
52
filePath: "Component.tsx"
53
}
54
);
55
```
56
57
### Version Information
58
59
Returns the current Sucrase version string.
60
61
```typescript { .api }
62
/**
63
* Get the current Sucrase version
64
* @returns Version string (e.g., "3.35.0")
65
*/
66
function getVersion(): string;
67
```
68
69
### Token Debugging
70
71
Returns a formatted string representation of parsed tokens for debugging purposes.
72
73
```typescript { .api }
74
/**
75
* Get formatted token representation for debugging
76
* @param code - Source code to tokenize
77
* @param options - Parsing options
78
* @returns Formatted token string
79
*/
80
function getFormattedTokens(code: string, options: Options): string;
81
```
82
83
## Transform Options
84
85
### Core Options Interface
86
87
Complete configuration interface for all transformation options.
88
89
```typescript { .api }
90
interface Options {
91
/** Array of transform names to apply */
92
transforms: Array<Transform>;
93
/** Opt out of all ES syntax transformations */
94
disableESTransforms?: boolean;
95
/** JSX transformation mode */
96
jsxRuntime?: "classic" | "automatic" | "preserve";
97
/** Compile for production (affects JSX transform) */
98
production?: boolean;
99
/** Custom JSX import source for automatic runtime */
100
jsxImportSource?: string;
101
/** Custom JSX pragma function for classic runtime */
102
jsxPragma?: string;
103
/** Custom JSX fragment pragma for classic runtime */
104
jsxFragmentPragma?: string;
105
/** Preserve type-only imports and exports */
106
keepUnusedImports?: boolean;
107
/** Don't transform dynamic import() expressions */
108
preserveDynamicImport?: boolean;
109
/** Use createRequire for TS import = require in ESM */
110
injectCreateRequireForImportRequire?: boolean;
111
/** Use TypeScript's legacy module interop behavior */
112
enableLegacyTypeScriptModuleInterop?: boolean;
113
/** Use Babel 5's legacy module interop behavior */
114
enableLegacyBabel5ModuleInterop?: boolean;
115
/** Source map generation options */
116
sourceMapOptions?: SourceMapOptions;
117
/** File path for error messages and source maps */
118
filePath?: string;
119
}
120
```
121
122
**Usage Examples:**
123
124
```typescript
125
// Minimal configuration
126
const basic: Options = {
127
transforms: ["typescript"]
128
};
129
130
// Production React configuration
131
const production: Options = {
132
transforms: ["typescript", "jsx"],
133
jsxRuntime: "automatic",
134
production: true,
135
sourceMapOptions: { compiledFilename: "bundle.js" }
136
};
137
138
// Legacy CommonJS configuration
139
const legacy: Options = {
140
transforms: ["typescript", "jsx", "imports"],
141
enableLegacyTypeScriptModuleInterop: true,
142
jsxRuntime: "classic",
143
jsxPragma: "React.createElement"
144
};
145
```
146
147
### Transform Types
148
149
Available transform names that can be combined in the transforms array.
150
151
```typescript { .api }
152
type Transform =
153
| "jsx" // JSX syntax transformation
154
| "typescript" // TypeScript type removal and features
155
| "flow" // Flow type annotation removal
156
| "imports" // ES modules to CommonJS conversion
157
| "react-hot-loader" // React hot loader support
158
| "jest"; // Jest method hoisting
159
```
160
161
**Transform Descriptions:**
162
163
- **jsx**: Transforms JSX syntax to function calls (React.createElement or jsx function)
164
- **typescript**: Removes TypeScript types, handles enums, namespace, and TS-specific syntax
165
- **flow**: Removes Flow type annotations and syntax
166
- **imports**: Converts ES modules (import/export) to CommonJS (require/module.exports)
167
- **react-hot-loader**: Adds React Hot Loader compatibility transformations
168
- **jest**: Hoists jest method calls above imports for proper test setup
169
170
### Source Map Options
171
172
Configuration for source map generation.
173
174
```typescript { .api }
175
interface SourceMapOptions {
176
/**
177
* The name to use in the "file" field of the source map.
178
* Should be the name of the compiled output file.
179
*/
180
compiledFilename: string;
181
}
182
```
183
184
### Options Validation
185
186
Validates an options object against the expected schema.
187
188
```typescript { .api }
189
/**
190
* Validate transform options
191
* @param options - Options object to validate
192
* @throws Error if options are invalid
193
*/
194
function validateOptions(options: Options): void;
195
```
196
197
## Transform Context
198
199
Internal transformation context used during processing (exported for advanced use cases).
200
201
```typescript { .api }
202
interface SucraseContext {
203
tokenProcessor: TokenProcessor;
204
scopes: Array<Scope>;
205
nameManager: NameManager;
206
importProcessor: CJSImportProcessor | null;
207
helperManager: HelperManager;
208
}
209
```
210
211
## Advanced Configuration Examples
212
213
### Modern ESM Build
214
```typescript
215
const esmConfig: Options = {
216
transforms: ["typescript", "jsx"],
217
jsxRuntime: "automatic",
218
injectCreateRequireForImportRequire: true,
219
preserveDynamicImport: true
220
};
221
```
222
223
### Legacy Browser Support
224
```typescript
225
const legacyConfig: Options = {
226
transforms: ["typescript", "jsx", "imports"],
227
jsxRuntime: "classic",
228
jsxPragma: "React.createElement",
229
jsxFragmentPragma: "React.Fragment",
230
enableLegacyBabel5ModuleInterop: true
231
};
232
```
233
234
### Testing Configuration
235
```typescript
236
const testConfig: Options = {
237
transforms: ["typescript", "jsx", "jest"],
238
disableESTransforms: true,
239
keepUnusedImports: false
240
};
241
```
242
243
### Development with Source Maps
244
```typescript
245
const devConfig: Options = {
246
transforms: ["typescript", "jsx"],
247
sourceMapOptions: { compiledFilename: "app.js" },
248
filePath: "src/app.tsx"
249
};
250
```