Directly import SVG in Next.js

Original link:


With the rise of SVG, the use of Sprite and IconFont as icons in the interface in the past is outdated. People will be more inclined to load simpler, smaller, easier to write SVG solutions for icons.

And Next.js also provides support for SVG.

The easiest way to load – URL loading

If you don’t want to make any improvements to the application, one of the easiest ways is to load directly using the path. Just use an img tag and set src to the path to the svg file.

 <img src="/logo.svg" alt="Logo SVG" />

However, the problem with using URL to load is that when your folder path and structure are complex, you need to use a long path to load SVG, which is more troublesome.

Of course, you can also simply optimize this solution – for example, encapsulate an svg component by yourself, which supports passing in file name & alt text and other parameters. In this way, you only need to enter the file name when calling.

The most comfortable loading method – programmatic loading

In Next.js, if you want to import SVG more comfortably, the better solution is to use the import tag to import. However, since SVG itself is not a standard React component, you need to install a plugin on Next.js to support parsing SVG.

Adding SVG parsing requires installing the @svgr/webpack plugin. Run the following command to install the plugin.

 # yarnyarn add @svgr/webpack# npmnpm install --save @svgr/webpack

After the installation is complete, modify next.config.js to add relevant parsing rules.

 module.exports = { webpack(config) { config.module.rules.push({ test: /\.svg$/, use: ["@svgr/webpack"] }); // 针对SVG 的处理规则return config; }};

After modification and saving, you can directly use the import syntax to process

 import Logo from "../assets/logo.svg";// usage<Logo />

In this way, you can directly import SVG as a Component, and use the React Component Props you are familiar with to modify the properties of this Component.


In this article, I share two methods in Next.js. You can decide which method to use to introduce SVG according to your actual situation.

This article is reprinted from:
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment

Your email address will not be published.