I am trying to change the default webpack loader for SVG files in Gatsby JS. I want to use the 'svg-url-loader' instead of the default 'url-loader'. I have installed it, and it works fine with webpack-inline-loaders.
But to avoid repeating the process, I decided to use the onCreateWebpackConfig Node API to change the loader for the SVG files. So I added the below code in the gatsby-node.js file.
exports.onCreateWebpackConfig = ({
stage,
getConfig,
rules,
loaders,
plugins,
actions,
}) => {
actions.setWebpackConfig({
module: {
rules: [
{
test: /\.svg/,
use: {
loader: "svg-url-loader",
options: {
limit: 4096,
iesafe: true,
},
},
},
],
},
});
};
But the website is now not displaying any SVG image but alt text. This is because the src attributes of those IMG tags are using a faulty base64 encoded image and not the UTF8 encoded SVG XML tag.
The console is not logging any errors. I have also tried creating a local plugin at the /plugins dir, but it doesn't work. I am developing my site on my local machine and building it using Gatsby Cloud. The problem exists in both places.
Here's the link to a minimal repro.
The problem here is that to use a custom loader in any framework, you have to disable the default loader first. Then you'll be able to add your custom loader. So, first, you have to disable the default, 'url-loader' and then set the 'svg-url-loader' for SVG files.
exports.onCreateWebpackConfig = ({
stage,
getConfig,
rules,
loaders,
plugins,
actions,
}) => {
const config = getConfig();
config.module.rules.find(
(rule) =>
rule.test &&
rule.test.toString() ===
"/\\.(ico|svg|jpg|jpeg|png|gif|webp|avif)(\\?.*)?$/"
).test = /\.(ico|jpg|jpeg|png|gif|webp|avif)(\?.*)?$/;
config.module.rules.push({
test: /\.svg/,
use: {
loader: "svg-url-loader",
options: {
limit: 4096,
iesafe: true,
},
},
});
actions.replaceWebpackConfig(config);
};