Rollup.js
SVGR provides an official rollup.js plugin to import SVG as React components.
Install
npm install --save-dev @svgr/rollup# or use yarnyarn add --dev @svgr/rollup
Usage
rollup.config.js
import svgr from '@svgr/rollup'export default {plugins: [svgr()],input: 'src/main.js',output: {file: 'bundle.js',format: 'cjs',},}
Your code
import Star from './star.svg'const App = () => (<div><Star /></div>)
Options
SVGR let you specify options in a runtime config file like svgr.config.js
or directly in the rollup.js plugin:
rollup.config.js
import svgr from '@svgr/rollup'export default {plugins: [svgr({ icon: true })],input: 'src/main.js',output: {file: 'bundle.js',format: 'cjs',},}
SVGR options reference describes all options available.
Using with @rollup/plugin-url
It is possible to use it with @rollup/plugin-url
.
rollup.config.js
import url from '@rollup/plugin-url'import svgr from '@svgr/rollup'export default {plugins: [url(), svgr({ icon: true })],input: 'src/main.js',output: {file: 'bundle.js',format: 'cjs',},}
Your code
import starUrl, { ReactComponent as Star } from './star.svg'const App = () => (<div><img src={starUrl} alt="star" /><Star /></div>)
The named export defaults to ReactComponent
, but can be customized with the namedExport
option.
Please note that by default, @svgr/rollup
will try to export the React Component via default export if there is no other plugin handling svg files with default export. When there is already any other plugin using default export for svg files, @svgr/rollup
will always export the React component via named export.
If you prefer named export in any case, you may set the exportType
option to named
.
Use your own Babel configuration
By default, @svgr/rollup
applies a babel transformation with optimized configuration. In some case you may want to apply a custom one (if you are using Preact for an example). You can turn off Babel transformation by specifying babel: false
in options.
Edit this page on GitHub{plugins: [svgr({ babel: false })]}