导入 svg 时出现 React vite typescript 错误 - 找不到模块 .svg?react

问题描述 投票:0回答:1

我已按照有关如何使用 vite-plugin-svgr 的说明进行操作。我已经安装了它并添加了一个用于类型推断的声明助手到

vite-env.d.ts
:

// / <reference types="vite/client" />
// / <reference types="vite-plugin-svgr/client" />

我的资产文件夹中有一个 svg 文件,我将其导入到我的组件中:

import Logo from '../assets/mountain.svg?react'

但是,我收到打字稿错误:

TS2307: Cannot find module '../assets/mountain.svg?react' or its corresponding type declarations.

如何避免这个错误?

我还尝试将 svg 类型声明为 ReactComponent:

declare module '*.svg' {
  import * as React from 'react'

  export const ReactComponent: React.FunctionComponent<
    React.SVGProps<SVGSVGElement> & { title?: string }
  >
}

然后像这样导入 svg:

import { ReactComponent as Logo } from '../assets/mountain.svg'

但是,然后我得到一个错误:

Uncaught SyntaxError: The requested module '/src/assets/mountain.svg?import' does not provide an export named 'ReactComponent'
reactjs typescript svg
1个回答
0
投票

以防万一它仍然有用

// / <reference types="vite/client" />
// / <reference types="vite-plugin-svgr/client" />

应该是

/// <reference types="vite/client" />
/// <reference types="vite-plugin-svgr/client" />

我遇到了同样的问题,通过这种方式解决了。

© www.soinside.com 2019 - 2024. All rights reserved.