【问题标题】:Cannot find module '../Theme/Icons/' or its corresponding type declarations.ts(2307)找不到模块“../Theme/Icons/”或其对应的类型声明.ts(2307)
【发布时间】:2021-10-16 15:09:17
【问题描述】:

我在 React-typescript 中有一个新项目,在那里我得到了一个 repo。文件夹结构如下:

parentDirectory
└───src   
│    │   Components
│    │   Store
│    │   Theme
|         │   Icons
│         │   Styles

我在 Icons 文件夹中有一些 svgpng 图标。我正在尝试将它们导入到 Components 文件夹中的文件中,但出现错误:

Cannot find module '../Theme/Icons/' or its corresponding type declarations.ts(2307)

我的导入语句如下。我也不确定这是否是正确的方法:

import  { svgComponent as Icon } from '../Theme/Icons/filename.svg'

tsconfig.json 如下:

{
  "compilerOptions": {
    "outDir": "dist",
    "module": "esnext",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "jsx": "react",
    "sourceMap": true,
    "declaration": true,
    "esModuleInterop": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist", "validationApp"]
}

当我使用导入时

import  Icon from '../Theme/Icons/filename.svg'

我收到以下错误:

(commonjs plugin) Error: ENOENT: no such file or directory, open 'C:\Users\my-app\src\Theme\Icons\filename.svg'

我习惯将图像存储在根目录下的public 文件夹中,然后导入。这个文件结构对我来说是新的,我不能改变它。如果需要,我将编辑问题并发布其他任何内容。对此的任何帮助表示赞赏。提前致谢。

【问题讨论】:

  • 你有没有试过这样做:import { default as Icon } from '../Theme/Icons/filename.svg'
  • @RyanLe 对我不起作用。

标签: reactjs typescript svg react-typescript react-tsx


【解决方案1】:

假设您正在使用 CreateReactApp 并且无权更新您的 webpack.config,这可能是您最好的选择。

在您的 .d.ts 文件中添加:

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

如果您还没有设置 .d.ts 文件,您可以创建一个新文件,例如custom.d.ts 在您的 src 目录中。

然后在你的 tsconfig.json 中确保你设置了这个选项:"include": [""src/custom.d.ts"]

【讨论】:

  • 不,我无权访问 webpack 配置。我刚刚重新检查了 repo,发现它有一个 typings.d.ts 文件。声明 declare module '*.svg' { const svgUrl: string; const svgComponent: SvgrComponent; export default svgUrl; export { svgComponent as ReactComponent } } 和 "include": ["src/typings.d.ts"] 没有解决问题
猜你喜欢
  • 1970-01-01
  • 2022-11-10
  • 2020-12-08
  • 2021-03-17
  • 2021-08-27
  • 2021-01-19
  • 2022-10-17
  • 2022-11-05
  • 2019-10-05
相关资源
最近更新 更多