When I try to import SVG Image then the following error shows. Which loader I have to use for importing SVG images?
./static/Rolling-1s-200px.svg 1:0
Module
Install next-images.
yarn add -D next-images
Create a next.config.js in your project
// next.config.js
const withImages = require('next-images')
module.exports = withImages()
I personally prefer next-react-svg plugin which allows to treat SVG images as React components and automatically inline them, similar to what Create React App does.
Here is how to use it:
next-react-svg
:npm i next-react-svg
next.config.js
:const withReactSvg = require('next-react-svg')
const path = require('path')
module.exports = withReactSvg({
include: path.resolve(__dirname, 'src/assets/svg'),
webpack(config, options) {
return config
}
})
The include
parameter is compulsory and it points to your SVG image folder.
If you already have any plugins enabled for your Next.js, consider using next-compose-plugins to properly combine them.
import Logo from 'assets/svg/Logo.svg';
export default () => (
<Logo />
);
That's it. From now on, Next.js will be including SVG images imported this way into the rendered markup as SVG tags.
This worked for me without any other dependency
// In next.config.js
const withSass = require('@zeit/next-sass');
const withCSS = require("@zeit/next-css");
module.exports = withCSS(withSass({
webpack (config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000
}
}
});
return config;
}
}));
You can use babel-plugin-inline-react-svg
import React from 'react';
import CloseSVG from './close.svg';
const MyComponent = () => <CloseSVG />;
npm install --save-dev babel-plugin-inline-react-svg
// .babelrc
{
"plugins": [
"inline-react-svg"
]
}
Or see the link for more instructions.
You can simply import it via img tag.
<img src='./next.svg' alt='next' />
Just make sure that the svg is in public folder.
You need to provide a webpack loader that will handle SVG imports, one of the famous one is svgr.
In order to configure it to work with next, you need to add to your next.config.js
file the usage of the loader, like that:
// next.config.js
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
issuer: {
test: /\.(js|ts)x?$/,
},
use: ['@svgr/webpack'],
});
return config;
},
};
For more config info, check out the docs.
Don't forget to install it first: npm install
@svgr/webpack
Edit
I've added issuer
section which strict these svg as component only for svgs that are imported from js / ts
files.
This Allows you to configure other behaviour for svg
s that are imported from other file types (such as .css
)