I am using bud with sage 10 and would like to use svgr (Webpack - SVGR) to include SVGs in my gutenberg blocks. Is there any documentation about howto accomplish this?
I somehow managed to load the SVGs directly using the SVGr webpack loader with !@svgr/webpack!../../svgs/image.svg'
but I would rather not specify the loader directly in the script files.
Apologies for resurrecting an old thread, but posting here in case anyone else runs into this looking for a solution. Mentioning Webpack-SVGR was a good starting point and following this from Bud’s documentation - Customizing loaders | bud.js - I arrived at the following solution:
- Install
@svgr/webpack
by running
yarn add @svgr/webpack --save-dev
- In
bud.config.ts
, add the code below. Note that Iunshift
the rule to add it at the beginning - there are some other SVG-related loaders that ended up giving me just the URL to the public SVG, instead of the React component.
bud.hooks.on(`build.module.rules.oneOf`, (rules = []) => {
rules.unshift({
test: /\.svg$/,
use: [`@svgr/webpack`],
});
return rules;
});
- Optionally add an alias in
bud.config.ts
:
bud.alias(`@icons`, bud.path(`resources/images/icons`));
- Also optionally I added the following alias in
tsconfig.json
(not sure if this is required or not ) - I added it to thecompilerOptions.paths
object
"@icons/*": ["images/icons/*"]
- Import the component in a block:
import FacebookIcon from '@icons/facebook-logo.svg';
- Use in your component :
<FacebookIcon />
The result is that the SVG is inlined, instead of being used via an src
attribute
Btw - I’m doing this in Radicle, but I would venture a guess that you can do the same in other Roots-based things as long as they use Bud as the build system.
I hope this helps!
3 Likes