I was getting this error when import svg in React/Typescript/Webpack 5 project:
Cannot find module '../path' or its corresponding type declarations.
then I added:
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement> & { title?: string }>;
const src: string;
export default src;
}
to the custom.d.ts
file. It works if I use the svg as an image src
. But I need to use the svg as an ReactElement because I need to change its content based on user clicks.
I tried to import svg as
import DislikeIcon from '../../media/icons/dislike.svg';
const Component = () => (<> <DislikeIcon /> </>)
then I got this error:
<data:image/svg... /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
then I tried:
import { ReactComponent as DislikeIcon } from '../../media/icons/dislike.svg';
and got:
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
My webpack.config.js file
module.exports = {
...
module: {
rules: [
{
test: /\.[jt]sx?$/,
use: ['babel-loader'],
exclude: /node_modules/,
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
test: /\.svg$/,
loader: 'url-loader',
},
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
{
test: /\.(woff(2)?|eot|ttf|otf)$/,
type: 'asset/inline',
},
],
},
...
};
my custom.d.ts file:
declare module '*.png' {
const value: string;
export = value;
}
declare module '*.jpg' {
const value: string;
export = value;
}
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement> & { title?: string }>;
const src: string;
export default src;
}
my tsconfig.json file:
{
"compilerOptions": {
"target": "ES5",
"module": "ESNext",
"moduleResolution": "node",
"lib": [
"DOM",
"ESNext"
],
"jsx": "react-jsx",
"noEmit": true,
"isolatedModules": true,
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"allowJs": true,
"checkJs": true,
},
"include": ["src/**/*", "./custom.d.ts"],
"exclude": ["node_modules", "build"],
}
I searched a lot for an answer, but everyone says something similar. This is taking me a time I don't have. Does anyone have any suggestion?
Thank you for you attention!