By default, Rsbuild will treat SVG files as static assets. For processing rules, please refer to: Import Static Assets。
With SVGR plugin, Rsbuild supports convert SVG to React components via SVGR.
You can install the plugin using the following command:
You can register the plugin in the rsbuild.config.ts
file:
After installing the plugin, When import an SVG in a JS file, if you import ReactComponent
, Rsbuild will call SVGR to convert the SVG into a React component.
At this time,if you use the default import, then the SVG will be treated as a normal static asset and you will get a URL:
If you need to customize the compilation behavior of Svgr, you can use the following configs.
Modify the options of SVGR, the passed object will be deep merged with the default value. See SVGR - Options for details.
import('@svgr/core').Config
Modify the default export type of SVG files.
'component' | 'url'
'url'
For example, set the default export as a React component:
Then import the SVG, you'll get a React component instead of a URL:
At this time, you can also specify the ?url
query to import the URL, for example:
When you reference an SVG asset in TypeScript code, TypeScript may prompt that the module is missing a type definition:
To fix this, you need to add a type declaration file for the SVG asset, please create a src/env.d.ts
file, and add the following type declaration:
If you set svgDefaultExport
to 'component'
, then change the type declaration to:
After adding the type declaration, if the type error still exists, you can try to restart the current IDE, or adjust the directory where env.d.ts
is located, making sure the TypeScript can correctly identify the type definition.