I am currently trying import .svg into next.js project but I failed.
I tried import .svg same way as in react project, that I created typing.d.ts and import svg like component. But it doesn't work.
declare module '*.svg' {
import React from 'react';
const src: string;
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
export default src;
}
Import svg example
- I using next.js - 12.1 and styled-components - 5.3.3
- example-import-svg
What I need?
- Import
.svg
file and change its width and height.
Has anyone had the same problem? Or did anyone manage to solve it?
Thank you
CodePudding user response:
Maybe a solution.
- Default option in next.js for
removeViewBox
istrue
. If you change in .svgheight
orwidth
the view-box from.svg
will be rest to default value. - If you use in your
next.config.js
webpack and setremoveViewBox
tofalse
.svg resize start work.
A working example: stackblitz-resize-svg-next.js
webpack(config) {
config.module.rules.push({
loader: '@svgr/webpack',
options: {
prettier: false,
svgo: true,
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: { removeViewBox: false },
},
},
],
},
titleProp: true,
},
test: /\.svg$/,
});
return config;
},
If you have in .babelrc
set "inline-react-svg"
this solution will not work.
CodePudding user response:
Another approach I've used, leverages svgo-loader
:
// Asset handling
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// SVG handler, inlines everything under 200KB
config.module.rules.push({
test: /\.svg$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 200 * 1024
}
},
use: 'svgo-loader'
});
return config;
},