So you want to use SVGs in Next.js as SVG and not as an image? Then this tutorial is for you!
Step 1: Install @svgr/webpack
This library allows us to import SVG as a React component. You do NOT need to install Webpack separately.
We'll install it as a dev
dependency. Run the command.
npm i @svgr/webpack --save-dev
Step 2: Configure Webpack
There will be a next.config.js
file in your project. If you do not have one, just create one.
Your next.config.js
should look something like this
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, } module.exports = nextConfig
Now add the following Webpack configuration in the nextConfig
object.
webpack(config){ config.module.rules.push({ test: /\.svg$/, use: [{loader: '@svgr/webpack', options: {icon: true}}] }) return config }
We're basically pre-processing our SVG files using loaders.
Finally, your next.config.js should look like this.
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, webpack(config){ config.module.rules.push({ test: /\.svg$/, use: [{loader: '@svgr/webpack', options: {icon: true}}] }) return config } } module.exports = nextConfig
Step 3: Importing SVG
Restart the dev
server first.
You can now import SVG just like any other React component.
import FacebookIcon from './facebook.svg' export const Home = ()=>{ return ( <FacebookIcon/> ) }
And, that's it ๐!
I hope you found my article helpful. Thanks for reading my post!
Top comments (1)
how does this affect performance?