Replies: 4 comments 6 replies
-
That's exactly how I did it. https://gist.github.com/lukebussey/8387bb038629dccc01a62487614f44df |
Beta Was this translation helpful? Give feedback.
-
Actually, you can avoid having to prefix the import with module.exports = {
webpack(config) {
const fileLoaderRule = config.module.rules.find(
(rule) => rule.test && rule.test.test('.svg'),
);
fileLoaderRule.exclude = /\.svg$/;
config.module.rules.push({
test: /\.svg$/,
loader: require.resolve('@svgr/webpack'),
});
return config;
},
}; |
Beta Was this translation helpful? Give feedback.
-
Shouldn't using SVG and Image be part of the standard documentation? |
Beta Was this translation helpful? Give feedback.
-
To support importing SVGs both as React components and as URLs (for use with
module.exports = {
webpack(config) {
// SVG as React component (default)
config.module.rules.push({
test: /\.svg$/,
issuer: /\.[jt]sx?$/,
resourceQuery: { not: [/url/] },
use: ["@svgr/webpack"],
});
// SVG as URL (for <Image src={...} />)
config.module.rules.push({
test: /\.svg$/,
resourceQuery: /url/, // *.svg?url
type: "asset/resource",
});
return config;
},
}; This lets you do: import Logo from './logo.svg'; // React component for <Logo />
import logoUrl from './logo.svg?url'; // string URL for <Image src={logoUrl} /> You’ll also need this in your TypeScript declarations: declare module "*.svg?url" {
const src: string;
export default src;
}
declare module "*.svg" {
import React = require("react");
const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
export default ReactComponent;
} This way, you get both import styles working in Next.js with TypeScript! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
The
<Image>
component makes it easy to display SVG images by importing them:However this conflicts with Babel plugins like babel-plugin-inline-react-svg or Webpack loaders like @svgr/webpack that allow you to import SVG images as React components:
I understand the implications of both approaches and when to use each. And I was wondering if the community had any preferred approaches for when you want to use both on the same codebase.
Ideally I'd leave
.svg
imports to Next.js (to avoid fighting against it) and opt into transforming to React components on a case by case basis.This works:
But I was hoping there was a more elegant solution than that. For example, I'd be fine with:
Not sure how to make that work though.
Any help and/or guidance would be appreciated.
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions