首页 > 解决方案 > 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"],
  }

我搜索了很多答案,但每个人都说类似的话。这花费了我没有的时间。有人有什么建议吗?

感谢您的关注!

标签: reactjstypescriptsvgwebpack

解决方案


推荐阅读