DEV Community

Cover image for Use SVGs with Next.js using svgr/webpack
Om Kathe
Om Kathe

Posted on

2 1 1 1 1

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
yash_suthar_c068881a433c6 profile image
Yash Suthar •

how does this affect performance?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay