打字稿 - 模块“*.svg""没有导出成员“ReactComponent" [英] TypeScript - Module '"*.svg"' has no exported member 'ReactComponent

查看:121
本文介绍了打字稿 - 模块“*.svg""没有导出成员“ReactComponent"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 TypeScript 导入一个 .svg 文件作为 React 组件.

I'm trying to import an .svg file as a React component with TypeScript.

根据 React 文档,这是这样做的:

According to the React docs, this is done like so:

import { ReactComponent as Icon } from './Icon.svg';

在 TypeScript 文档之后,我添加了这个:

Following the TypeScript docs, I've added this:

// custom.ts.d

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

// tsconfig.json

{
    ...
    "files": [
        "custom.d.ts"
    ]
}

SVG 正在渲染.但是我收到了一个 TypeScript 错误:

The SVG is rendering. But I'm getting a TypeScript error:

[ts] 模块 '"*.svg"' 没有导出成员 'ReactComponent'.[2305]

如果有帮助,这是我的完整 tsconfig 文件:

Here is my full tsconfig file if that helps:

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./dist",
    "strict": true,
    "jsx": "react",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": false,
    "preserveConstEnums": true,
    "sourceMap": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "baseUrl": ".",
    "plugins": [
      {
        "name": "typescript-styled-plugin"
      }
    ],
    "typeRoots": ["./node_modules/@types"],
    "lib": ["dom", "es2015", "es2017"]
  },
  "exclude": ["node_modules", "dist"],
  "files": [
    "custom.d.ts"
  ]
}

谢谢!

推荐答案

您有 export default content; 但是您正在执行 named 导入(不是默认导入).

You have export default content; But you are doing a named import (not a default import).

更改声明以导出您要导入的名称:

Change declaration to export the name you are importing:

declare module '*.svg' {
  import React = require('react');
  export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
  const src: string;
  export default src;
}

附加

建议不要在 tsconfig.json 中使用 files.而是使用 include

这篇关于打字稿 - 模块“*.svg""没有导出成员“ReactComponent"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆