0
# @vitejs/plugin-react-swc
1
2
@vitejs/plugin-react-swc is a high-performance Vite plugin that integrates SWC (Speedy Web Compiler) as the JavaScript/TypeScript transformer for React applications, providing significantly faster Fast Refresh (~20x faster than Babel) and automatic JSX runtime transformation.
3
4
## Package Information
5
6
- **Package Name**: @vitejs/plugin-react-swc
7
- **Package Type**: npm (Vite plugin)
8
- **Language**: TypeScript
9
- **Installation**: `npm install -D @vitejs/plugin-react-swc`
10
11
## Core Imports
12
13
```typescript
14
import react from '@vitejs/plugin-react-swc';
15
```
16
17
For CommonJS environments:
18
19
```javascript
20
const react = require('@vitejs/plugin-react-swc');
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { defineConfig } from 'vite';
27
import react from '@vitejs/plugin-react-swc';
28
29
export default defineConfig({
30
plugins: [react()],
31
});
32
```
33
34
With options:
35
36
```typescript
37
import { defineConfig } from 'vite';
38
import react from '@vitejs/plugin-react-swc';
39
40
export default defineConfig({
41
plugins: [
42
react({
43
jsxImportSource: '@emotion/react',
44
tsDecorators: true,
45
devTarget: 'es2022',
46
}),
47
],
48
});
49
```
50
51
## Architecture
52
53
The plugin returns an array of specialized Vite plugins that handle different phases of the development and build process:
54
55
- **Runtime Resolver**: Resolves React refresh runtime during development for HMR functionality
56
- **Development Transformer**: Handles SWC-based transformation during development with Fast Refresh support
57
- **Production Transformer**: Handles optimized transformation for production builds (conditionally applied based on SWC plugin usage)
58
59
The plugin automatically configures Vite to disable esbuild transformation and uses SWC for all React-related file processing, with intelligent file type detection and parsing based on file extensions.
60
61
## Capabilities
62
63
### Main Plugin Function
64
65
Creates a Vite plugin configuration for React with SWC transformation.
66
67
```typescript { .api }
68
/**
69
* Creates a Vite plugin configuration for React with SWC transformation
70
* @param options - Configuration options for the plugin
71
* @returns Array of Vite plugins for React development
72
*/
73
declare function react(options?: Options): Plugin[];
74
75
interface Options {
76
/** Control where the JSX factory is imported from (default: "react") */
77
jsxImportSource?: string;
78
/** Enable TypeScript decorators. Requires experimentalDecorators in tsconfig (default: false) */
79
tsDecorators?: boolean;
80
/** Use SWC plugins. Enable SWC at build time */
81
plugins?: [string, Record<string, any>][];
82
/** Set the target for SWC in dev. This can avoid to down-transpile private class method (default: "es2020") */
83
devTarget?: JscTarget;
84
/** Override the default include list (.ts, .tsx, .mts, .jsx, .mdx) */
85
parserConfig?: (id: string) => ParserConfig | undefined;
86
/** React Fast Refresh runtime URL prefix for module federation context */
87
reactRefreshHost?: string;
88
/** Direct SWC options mutation - use at your own risk */
89
useAtYourOwnRisk_mutateSwcOptions?: (options: SWCOptions) => void;
90
/** If set, disables the recommendation to use @vitejs/plugin-react */
91
disableOxcRecommendation?: boolean;
92
}
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
// Basic usage with no options
99
export default defineConfig({
100
plugins: [react()],
101
});
102
103
// With JSX import source for Emotion
104
export default defineConfig({
105
plugins: [
106
react({
107
jsxImportSource: '@emotion/react',
108
}),
109
],
110
});
111
112
// With TypeScript decorators support
113
export default defineConfig({
114
plugins: [
115
react({
116
tsDecorators: true,
117
}),
118
],
119
});
120
121
// With SWC plugins for styled-components
122
export default defineConfig({
123
plugins: [
124
react({
125
plugins: [['@swc/plugin-styled-components', {}]],
126
}),
127
],
128
});
129
130
// With custom development target
131
export default defineConfig({
132
plugins: [
133
react({
134
devTarget: 'es2022',
135
}),
136
],
137
});
138
139
// Module federation setup
140
export default defineConfig({
141
plugins: [
142
react({
143
reactRefreshHost: 'http://localhost:3000',
144
}),
145
],
146
});
147
```
148
149
### Custom Parser Configuration
150
151
Allows overriding the default file processing rules for advanced use cases.
152
153
```typescript { .api }
154
/**
155
* Custom parser configuration function
156
* @param id - File path/identifier to check
157
* @returns Parser configuration for the file, or undefined to skip processing
158
*/
159
type ParserConfigFunction = (id: string) => ParserConfig | undefined;
160
161
interface ParserConfig {
162
/** Parser syntax type */
163
syntax: 'typescript' | 'ecmascript';
164
/** Enable JSX parsing */
165
jsx?: boolean;
166
/** Enable TSX parsing (TypeScript + JSX) */
167
tsx?: boolean;
168
/** Enable decorator support */
169
decorators?: boolean;
170
}
171
```
172
173
**Usage Examples:**
174
175
```typescript
176
// Custom file extension support
177
export default defineConfig({
178
plugins: [
179
react({
180
parserConfig(id) {
181
// Support ReScript files compiled to JSX
182
if (id.endsWith('.res')) {
183
return { syntax: 'ecmascript', jsx: true };
184
}
185
// Custom TypeScript configuration
186
if (id.endsWith('.ts')) {
187
return { syntax: 'typescript', tsx: false, decorators: true };
188
}
189
},
190
}),
191
],
192
});
193
```
194
195
### SWC Integration Options
196
197
Advanced SWC configuration for specialized build requirements.
198
199
```typescript { .api }
200
/**
201
* SWC target compilation options
202
*/
203
type JscTarget =
204
| 'es3' | 'es5' | 'es2015' | 'es2016' | 'es2017' | 'es2018'
205
| 'es2019' | 'es2020' | 'es2021' | 'es2022' | 'es2023' | 'es2024' | 'esnext';
206
207
/**
208
* SWC plugin configuration tuple
209
*/
210
type SWCPlugin = [string, Record<string, any>];
211
212
/**
213
* Complete SWC options interface (for advanced mutation)
214
*/
215
interface SWCOptions {
216
/** The filename associated with the code being compiled */
217
filename?: string;
218
/** Enable searching for .swcrc configuration files */
219
swcrc?: boolean;
220
/** Enable searching for configuration files */
221
configFile?: boolean;
222
/** Enable source map generation */
223
sourceMaps?: boolean;
224
/** The working directory for resolving paths */
225
cwd?: string;
226
/** Module specifier for input source map */
227
inputSourceMap?: boolean | string;
228
/** JavaScript Compiler (JSC) configuration */
229
jsc?: {
230
/** Compilation target */
231
target?: JscTarget;
232
/** Parser configuration */
233
parser?: ParserConfig;
234
/** Experimental features */
235
experimental?: {
236
/** SWC plugins to apply */
237
plugins?: SWCPlugin[];
238
};
239
/** Transform configuration */
240
transform?: {
241
/** Enable useDefineForClassFields */
242
useDefineForClassFields?: boolean;
243
/** React-specific transformations */
244
react?: ReactConfig;
245
};
246
};
247
}
248
```
249
250
**Usage Examples:**
251
252
```typescript
253
// Advanced SWC options mutation
254
export default defineConfig({
255
plugins: [
256
react({
257
useAtYourOwnRisk_mutateSwcOptions(options) {
258
// Enable experimental decorator version
259
options.jsc.parser.decorators = true;
260
options.jsc.transform.decoratorVersion = '2022-03';
261
262
// Custom experimental features
263
options.jsc.experimental = {
264
...options.jsc.experimental,
265
plugins: [
266
['@swc/plugin-emotion', { autoLabel: true }],
267
],
268
};
269
},
270
}),
271
],
272
});
273
```
274
275
## Types
276
277
### Core Plugin Types
278
279
```typescript { .api }
280
/** Vite plugin interface from 'vite' package */
281
interface Plugin {
282
name: string;
283
apply?: 'build' | 'serve' | ((config: UserConfig, env: ConfigEnv) => boolean);
284
enforce?: 'pre' | 'post';
285
// ... additional Vite plugin properties
286
}
287
288
/** React configuration for SWC transformation */
289
interface ReactConfig {
290
/** JSX runtime mode */
291
runtime?: 'automatic' | 'classic' | 'preserve';
292
/** Enable development mode features */
293
development?: boolean;
294
/** Enable React Fast Refresh */
295
refresh?: boolean | {
296
refreshReg?: string;
297
refreshSig?: string;
298
emitFullSignatures?: boolean;
299
};
300
/** Module specifier for importing jsx/jsxs factory functions */
301
importSource?: string;
302
/** Replace the function used when compiling JSX expressions */
303
pragma?: string;
304
/** Replace the component used when compiling JSX fragments */
305
pragmaFrag?: string;
306
/** Throw error if XML namespaced tag name is used */
307
throwIfNamespace?: boolean;
308
}
309
```
310
311
### File Processing Types
312
313
```typescript { .api }
314
/** SWC transformation output */
315
interface Output {
316
/** Transformed code */
317
code: string;
318
/** Source map (not base64 encoded) */
319
map?: string;
320
}
321
```
322
323
## Error Handling
324
325
The plugin includes enhanced error handling that:
326
327
- Catches SWC transformation errors and extracts precise line/column information
328
- Provides detailed error messages with file locations for debugging
329
- Maintains source map accuracy for proper error reporting in development tools
330
331
Common error scenarios:
332
- **Syntax Errors**: Invalid TypeScript/JSX syntax in source files
333
- **Decorator Errors**: Using decorators without proper TypeScript configuration
334
- **Plugin Errors**: Issues with SWC plugins or incompatible plugin configurations
335
- **Target Compatibility**: Using language features not supported by the specified `devTarget`
336
337
## Platform Requirements
338
339
- **Node.js**: ^20.19.0 || >=22.12.0
340
- **Vite**: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
341
- **Dependencies**: @swc/core ^1.13.2, @rolldown/pluginutils 1.0.0-beta.32
342
343
## Performance Characteristics
344
345
- **Fast Refresh**: ~20x faster than Babel-based alternatives
346
- **File Processing**: Supports .tsx, .ts, .mts, .jsx, .mdx files by default
347
- **Build Optimization**: Conditional SWC usage in production based on plugin configuration
348
- **Memory Efficiency**: Lazy evaluation and efficient transformation pipelines