Use SVGs with Next.js using svgr/webpack

itsomkathe

Om Kathe

Posted on November 4, 2022

Use SVGs with Next.js using svgr/webpack

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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/>
    )
}
Enter fullscreen mode Exit fullscreen mode

And, that's it 🎉!

I hope you found my article helpful. Thanks for reading my post!

💖 💪 🙅 🚩
itsomkathe
Om Kathe

Posted on November 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related