如何在React中导入svg文件?

5
我有一个自定义的React + Typescript + Webpack项目。我需要导入一个简单的.svg文件并在组件中使用它。Typescript报告了以下错误:

找不到模块

我已经安装了svgr,将其添加到了我的webpack配置中,创建了一个custom.d.ts文件以允许在typescript中导入svg,并在tsconfig.json中指定了它。但是什么都没有起作用(目前我在Storybook中运行组件)。
这是我的webpack配置:

 module: {
      rules: [
        {
          test: /\.(ts|js)x?$/,
          exclude: /node_modules/,
          use: { loader: "babel-loader" },
        },
        { test: /\.css$/, use: ["style-loader", "css-loader"] },
        { test: /\.svg$/, use: ["@svgr/webpack"] },
        { test: /\.(png|svg|jpg|gif)$/, use: ["file-loader"] },
      ],
    },

我的组件

import React, { useEffect } from "react";
import Account from "./account.svg";

export default function Icon({ icon }) {
  return (
    <div>
      <Account/>
    </div>
  );
}

定制.d.ts文件

declare module "*.svg" {
  const content: any;
  export default content;
}

// added to tsconfig.json
"include": ["./src/**/*", "./custom.d.ts"],

这个svg是一个简单的<svg><path blabla/></svg>文件。

如何修复它?

1个回答

3
我遇到了同样的问题,并在这里找到了解决方案。
我个人使用了以下方法:
  1. 将我的徽标作为ReactComponent导入。

  2. 然后在我的代码中使用它 :)

import React from "react";
import { ReactComponent as MySvgFile } from "path/to/file.svg";

export default function MyComponent() {
  return (
    <div>
      <MySvgFile />
    </div>
  );
}


<Logo /> 是从哪里来的?你会用 mySvgFile 做什么? - grreeenn
抱歉,那是我的真实组件名称!我会更正为<mySvgFile />! - Sacha Pignot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接