![]()
Add SVG file inside HTML Img
You probably often use SVG file inside img tag like this:
<img src="my.svg" alt="SVG Dude" />but in Next js you can’t do that by default, therefore one of the solution is using plugins called “next-images”.
Install next-images
npm install --save next-images
# or
yarn add next-images -DAdd the plugins to nextjs configuration
// next.config.js
const withImages = require("next-images");
module.exports = withImages();Use SVG file as a React component
Sometimes it always great if you can directly import the SVG as Component like this:
import MySvg from "my.svg";
const MyApp = () => (
<div class="app">
<MySvg />
</div>
);well, there’s 2 way for that
1. Using “babel-plugin-inline-react-svg”
I’ve tried this with Next js and works nice unless you are using some kind of gradient effect in your SVG file (in my case it’s linearGradient), this doesn’t play nice with it, if that your case then go ahead to number 2
Install plugins
npm install --save-dev babel-plugin-inline-react-svg
# or
yarn add babel-plugin-inline-react-svg -DEdit your babelrc file
//.babelrc
{
"presets": ["next/babel"],
"plugins": ["inline-react-svg"]
}2. Using “@svgr/webpack”
Install plugins
npm install @svgr/webpack --save-dev
# or
yarn add @svgr/webpack -DEdit next.config.js
// next.config.js
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
issuer: {
test: /\.(js|ts)x?$/,
},
use: ["@svgr/webpack"],
});
return config;
},
};