0
# @svgr/webpack
1
2
@svgr/webpack is a webpack loader that transforms SVG files into React components during the build process. It integrates the SVGR transformation system with webpack's module loading, allowing developers to import SVG files as React components with full TypeScript support and extensive configuration options.
3
4
## Package Information
5
6
- **Package Name**: @svgr/webpack
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @svgr/webpack --save-dev`
10
11
## Core Imports
12
13
The package exports a default webpack loader function:
14
15
```javascript
16
// webpack.config.js
17
module.exports = {
18
module: {
19
rules: [
20
{
21
test: /\.svg$/,
22
use: ['@svgr/webpack'],
23
},
24
],
25
},
26
};
27
```
28
29
## Basic Usage
30
31
```javascript
32
// webpack.config.js - Basic SVG to React component transformation
33
{
34
test: /\.svg$/,
35
use: ['@svgr/webpack'],
36
}
37
```
38
39
```javascript
40
// In your React code
41
import Star from './star.svg';
42
43
const App = () => (
44
<div>
45
<Star />
46
</div>
47
);
48
```
49
50
## Architecture
51
52
@svgr/webpack is built on several key components:
53
54
- **Webpack Loader Interface**: Integrates with webpack's module loading system using the standard loader API
55
- **SVGR Core Integration**: Uses @svgr/core's transform function for SVG to JSX conversion
56
- **Babel Pipeline**: Optional Babel transformation for React/TypeScript code generation
57
- **Export Detection**: Automatically detects and handles existing module exports from other loaders
58
- **Configuration System**: Supports all SVGR configuration options plus webpack-specific settings
59
60
## Capabilities
61
62
### Webpack Loader
63
64
Main webpack loader function that processes SVG files and transforms them into React components.
65
66
```typescript { .api }
67
/**
68
* SVGR webpack loader function
69
* @param contents - SVG file contents as string
70
* @returns void (uses webpack's callback system)
71
*/
72
function svgrLoader(
73
this: webpack.LoaderContext<LoaderOptions>,
74
contents: string,
75
): void;
76
77
interface LoaderOptions extends Config {
78
babel?: boolean;
79
}
80
```
81
82
### Configuration Options
83
84
Complete configuration interface extending SVGR core options with webpack-specific settings.
85
86
```typescript { .api }
87
interface Config {
88
ref?: boolean;
89
titleProp?: boolean;
90
descProp?: boolean;
91
expandProps?: boolean | 'start' | 'end';
92
dimensions?: boolean;
93
icon?: boolean | string | number;
94
native?: boolean;
95
svgProps?: {
96
[key: string]: string;
97
};
98
replaceAttrValues?: {
99
[key: string]: string;
100
};
101
runtimeConfig?: boolean;
102
typescript?: boolean;
103
prettier?: boolean;
104
prettierConfig?: PrettierOptions;
105
svgo?: boolean;
106
svgoConfig?: SvgoConfig;
107
configFile?: string;
108
template?: TransformOptions['template'];
109
memo?: boolean;
110
exportType?: 'named' | 'default';
111
namedExport?: string;
112
jsxRuntime?: 'classic' | 'classic-preact' | 'automatic';
113
jsxRuntimeImport?: {
114
source: string;
115
namespace?: string;
116
specifiers?: string[];
117
defaultSpecifier?: string;
118
};
119
jsx?: {
120
babelConfig?: BabelTransformOptions;
121
};
122
}
123
```
124
125
**Usage Examples:**
126
127
```javascript
128
// Basic configuration with options
129
{
130
test: /\.svg$/,
131
use: [
132
{
133
loader: '@svgr/webpack',
134
options: {
135
native: true,
136
typescript: true,
137
svgo: false,
138
},
139
},
140
],
141
}
142
143
// With custom SVG props
144
{
145
test: /\.svg$/,
146
use: [
147
{
148
loader: '@svgr/webpack',
149
options: {
150
svgProps: { role: 'img' },
151
replaceAttrValues: { '#000': 'currentColor' },
152
},
153
},
154
],
155
}
156
```
157
158
### Loader Integration with Other Loaders
159
160
Seamless integration with other webpack loaders like url-loader for dual-purpose SVG handling.
161
162
```javascript { .api }
163
// Usage with url-loader for both component and URL exports
164
{
165
test: /\.svg$/,
166
use: ['@svgr/webpack', 'url-loader'],
167
}
168
```
169
170
**Usage Example:**
171
172
```javascript
173
// Dual import - both as React component and as URL
174
import starUrl, { ReactComponent as Star } from './star.svg';
175
176
const App = () => (
177
<div>
178
<img src={starUrl} alt="star" />
179
<Star />
180
</div>
181
);
182
```
183
184
### Custom Babel Configuration
185
186
Disable built-in Babel transformation to use custom Babel configuration.
187
188
```javascript { .api }
189
// Webpack configuration with custom Babel
190
{
191
test: /\.svg$/,
192
use: [
193
{
194
loader: 'babel-loader',
195
options: {
196
presets: ['preact', 'env'],
197
},
198
},
199
{
200
loader: '@svgr/webpack',
201
options: { babel: false },
202
}
203
],
204
}
205
```
206
207
### Rule-Based Configuration
208
209
Advanced webpack configuration for different file contexts using Rule.issuer.
210
211
```javascript { .api }
212
// Different handling for JavaScript vs CSS imports
213
[
214
{
215
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
216
issuer: /\.[jt]sx?$/,
217
use: ['babel-loader', '@svgr/webpack', 'url-loader'],
218
},
219
{
220
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
221
loader: 'url-loader',
222
},
223
]
224
```
225
226
## Types
227
228
### LoaderOptions
229
230
Configuration options specific to the webpack loader.
231
232
```typescript { .api }
233
interface LoaderOptions extends Config {
234
/** Enable/disable Babel transformation (default: true) */
235
babel?: boolean;
236
}
237
```
238
239
### Config
240
241
Complete SVGR configuration interface with all available options.
242
243
```typescript { .api }
244
interface Config {
245
ref?: boolean;
246
titleProp?: boolean;
247
descProp?: boolean;
248
expandProps?: boolean | 'start' | 'end';
249
dimensions?: boolean;
250
icon?: boolean | string | number;
251
native?: boolean;
252
svgProps?: {
253
[key: string]: string;
254
};
255
replaceAttrValues?: {
256
[key: string]: string;
257
};
258
runtimeConfig?: boolean;
259
typescript?: boolean;
260
prettier?: boolean;
261
prettierConfig?: PrettierOptions;
262
svgo?: boolean;
263
svgoConfig?: SvgoConfig;
264
configFile?: string;
265
template?: TransformOptions['template'];
266
memo?: boolean;
267
exportType?: 'named' | 'default';
268
namedExport?: string;
269
jsxRuntime?: 'classic' | 'classic-preact' | 'automatic';
270
jsxRuntimeImport?: {
271
source: string;
272
namespace?: string;
273
specifiers?: string[];
274
defaultSpecifier?: string;
275
};
276
jsx?: {
277
babelConfig?: BabelTransformOptions;
278
};
279
}
280
```
281
282
### State
283
284
Processing state information passed to SVGR transformation plugins.
285
286
```typescript { .api }
287
interface State {
288
filePath?: string;
289
componentName: string;
290
caller?: {
291
name?: string;
292
previousExport?: string | null;
293
defaultPlugins?: ConfigPlugin[];
294
};
295
}
296
```
297
298
### External Types
299
300
External type definitions from dependencies used in the API.
301
302
```typescript { .api }
303
// From Prettier
304
interface PrettierOptions {
305
[key: string]: any;
306
}
307
308
// From SVGO
309
interface SvgoConfig {
310
plugins?: string[] | object[];
311
[key: string]: any;
312
}
313
314
// From @svgr/babel-preset
315
interface TransformOptions {
316
template?: (variables: any, context: any) => any;
317
[key: string]: any;
318
}
319
320
// From @babel/core
321
interface BabelTransformOptions {
322
presets?: any[];
323
plugins?: any[];
324
[key: string]: any;
325
}
326
327
// From @svgr/core
328
interface ConfigPlugin {
329
(code: string, config: Config, state: State): string;
330
}
331
```
332
333
### Webpack Types
334
335
Webpack-specific type definitions used by the loader.
336
337
```typescript { .api }
338
// Simplified webpack LoaderContext interface (from webpack)
339
namespace webpack {
340
interface LoaderContext<TOptions> {
341
cacheable(): void;
342
async(): (err?: Error, result?: string) => void;
343
getOptions(): TOptions;
344
resourcePath: string;
345
fs: {
346
readFile(path: string, callback: (err: Error | null, data?: Buffer) => void): void;
347
};
348
}
349
}
350
```
351
352
## Export Behavior
353
354
The loader automatically detects and handles different export scenarios:
355
356
- **Standalone Usage**: Exports React component as default export
357
- **With Other Loaders**: Exports React component as named export (default: `ReactComponent`)
358
- **Custom Named Export**: Configurable via `namedExport` option
359
- **Export Type Control**: Force named export via `exportType: 'named'`
360
361
## Error Handling
362
363
The loader handles errors through webpack's standard callback mechanism:
364
365
- **Babel Transformation Errors**: Throws "Error while transforming using Babel"
366
- **File System Errors**: Propagated through webpack's error callback
367
- **SVGR Transform Errors**: Passed through from @svgr/core transformation process
368
369
## Advanced Configuration
370
371
### TypeScript Integration
372
373
```javascript
374
{
375
test: /\.svg$/,
376
use: [
377
{
378
loader: '@svgr/webpack',
379
options: {
380
typescript: true,
381
prettier: false,
382
svgo: true,
383
svgoConfig: {
384
plugins: ['preset-default', 'removeViewBox'],
385
},
386
},
387
},
388
],
389
}
390
```
391
392
### Custom Template Function
393
394
```javascript
395
{
396
test: /\.svg$/,
397
use: [
398
{
399
loader: '@svgr/webpack',
400
options: {
401
template: (variables, { tpl }) => {
402
return tpl`
403
${variables.imports};
404
${variables.interfaces};
405
406
const ${variables.componentName} = (${variables.props}) => (
407
${variables.jsx}
408
);
409
410
export default ${variables.componentName};
411
`;
412
},
413
},
414
},
415
],
416
}
417
```