SVG (Scalable Vector Graphics) is a highly useful image format in web development due to its ability to maintain image quality across various sizes. However, integrating SVGs into a Next.js application is often considered complicated. This article provides a practical guide on how to effectively integrate SVGs into your Next.js project.
Building the Folder Structure
To integrate SVGs into your Next.js application, create an assets folder within src. Place your SVG files inside this folder.
src/
|── assets/
│ └── logo.svg
└── pages/
Configuring Webpack for SVGs
To use SVGs as React components, you need to configure Webpack and install @svgr/webpack
.
Install @svgr/webpack
with the following command:
npm install @svgr/webpack --save-dev
Open the next.config.js
file in the root of your project.
Add the following configuration to integrate @svgr/webpack
:
// next.config.js
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack'],
});
return config;
},
};
Using SVGs in React Components
Import the SVG file that you placed in the src/assets
folder:
import Logo from '@/src/assets/logo.svg';
Use the SVG in your React component as follows:
import Logo from '../src/assets/logo.svg';
export default function HomePage() {
return (
<div>
<h1>Selamat Datang di Website Kami!</h1>
<Logo width={100} height={100} />
</div>
);
}
Conclusion
By following these steps, you can easily integrate SVGs into your Next.js application, enhancing both the design and performance of your project. An organized folder structure and proper configuration will help you make the most of SVGs.
Top comments (1)
I'll be honest, I thought modern versions of NextJS had that preconfigured and didn't need this customisation?
Edit: yeah, all versions after V10, which released 4 years ago