The quick way: <img>
or <Image>
Not suitable for interactive SVGs or if you intend to manipulate a SVG by external CSS/JS
One can use the official next/image
component or img
tag (as mentioned in this answer).
You just need to move your svg
file to public
instead of static
, and do something like this:
import Image from 'next/image';
// ...
<Image src="/Rolling-1s-200px.svg" width="2000" height="2000" />
But by using this method, the content of svg
file will not be present directly in the response; the browser will get an <img src="..." ...></img>
tag.
Also one needs to specify width
and height
, but you can calculate it from the viewbox
attribute.
On Next.js v11 and above, you can also do:
import Image from 'next/image';
import Illustration from '../static/Rolling-1s-200px.svg';
// ...
<Image src={Illustration} />
// one needs to use `Illustration.src` to get the source URL
// <img src={Illustration.src} ... />
Including SVG inside HTML (for webpack-5, TS)
The accepted answer has shown how to do this with webpack-4
, but since webpack-5
is now default, I'm sharing the appropriate config. You can use it after installing @svgr/webpack
(yarn add -D @svgr/webpack
or npm install @svgr/webpack --save-dev
):
// next.config.js
// https://github.com/gregberge/svgr/issues/551#issuecomment-839772396
module.exports = {
// other configs...
// future: { webpack5: true }, // -- not needed since Next.js v11.0.0
webpack(config) {
config.module.rules.push({
test: /\.svg$/i,
issuer: { and: [/\.(js|ts|md)x?$/] },
use: [
{
loader: '@svgr/webpack',
options: {
prettier: false,
svgo: true,
svgoConfig: { plugins: [{ removeViewBox: false }] },
titleProp: true,
},
},
],
});
return config;
},
};
If you are not using options
for the loader, then you can simply write this:
use: ['@svgr/webpack']
If you are using v6 of @svgr/webpack
then you need to specify SVGO config like this:
// ...
plugins: [
{
name: 'preset-default',
params: {
overrides: { removeViewBox: false },
},
},
],
// ...
If using typescript, you need to define proper modules (in the directory from where you are importing svg
, or maybe add it at root as <some-name>.d.ts
and include it tsconfig
):
// index.d.ts
declare module '*.svg' {
const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
export default ReactComponent;
}
Then you may use it like:
import Illustration from '../static/Rolling-1s-200px.svg';
// ...
<Illustration />
Note: Next.js v11.0.1+ have declared SVGs as modules exporting any
. Your custom configuration will not override the types set by next-env.d.ts
unless you exclude the latter. Please refer this.
[OUTDATED (Fixed)] UPDATE :
If you are using Next.js v11.0.0, then you might be getting errors while importing SVGs. Please update to v11.0.1
or above. Please follow the workaround mentioned in this comment.