reactjs - React/Typescript 无法将 svg 文件作为组件导入
问题描述
在 React/Typescript/Webpack 5 项目中导入 svg 时出现此错误:
Cannot find module '../path' or its corresponding type declarations.
然后我补充说:
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement> & { title?: string }>;
const src: string;
export default src;
}
到custom.d.ts
文件。如果我使用 svg 作为图像,它会起作用src
。但我需要将 svg 用作 ReactElement,因为我需要根据用户点击来更改其内容。
我尝试将 svg 导入为
import DislikeIcon from '../../media/icons/dislike.svg';
const Component = () => (<> <DislikeIcon /> </>)
然后我收到了这个错误:
<data:image/svg... /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
然后我尝试了:
import { ReactComponent as DislikeIcon } from '../../media/icons/dislike.svg';
并得到:
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.
我的 webpack.config.js 文件
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',
},
],
},
...
};
我的 custom.d.ts 文件:
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;
}
我的 tsconfig.json 文件:
{
"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"],
}
我搜索了很多答案,但每个人都说类似的话。这花费了我没有的时间。有人有什么建议吗?
感谢您的关注!
解决方案
推荐阅读
- c# - Visual Studio C# 应用程序连接到 MySql 服务器
- java - 列中带有 ImageView 数组的 JavaFX TableView
- asp.net-core - 如何在 MVC 核心 2.0 中使用 DisplayTemplates
- python - python:如何拆分按第一列分组的excel文件
- xpath - xpath 查询到页面上的特定数字
- android - 如何将亚马逊波利文本中的简历添加到 android 中的语音中?
- jquery - jQuery函数不在页面加载时调用
- javascript - 如何在js中连接对象属性
- firebase - 如何处理 Firebase 登录作为首次访问
- java - Appium 收集任何屏幕上的所有文本