Typescript 图像导入

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

我在这里找到了解决方案:Webpack & Typescript 图像导入

但是我遇到了错误:

[ts]
Types of property 'src' are incompatible.
  Type 'typeof import("*.png")' is not assignable to type 'string | undefined'.
    Type 'typeof import("*.png")' is not assignable to type 'string'.

我想我需要以某种方式强制导入,但不知道如何操作。 我在 React 中这样做。我看到

src
属性定义为
string | undefined
,这就是弹出错误的原因。

这是代码:

import * as Logo from 'assets/images/logo.png';

HTML:

<img src={Logo} alt="" />

以及基于上述解决方案的定义:

declare module "*.png" {
  const value: string;
  export default value;
}

Tsconfig:

{
  "compilerOptions": {
    "baseUrl": "./",
    "jsx": "react",
    "lib": ["es5", "es6", "dom"],
    "module": "commonjs",
    "noImplicitAny": false,
    "outDir": "./dist/",
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es5",
    "typeRoots": [
      "custom_typings"
    ]
  },
  "include": ["./src/**/*.tsx"],
  "exclude": ["dist", "build", "node_modules"]
}
reactjs typescript module tsconfig react-tsx
4个回答
179
投票

消除该错误的方法之一是修改 d.ts 文件,如下所示:

declare module "*.png"

删除

{
  const value: string;
  export default value;
}

或者您也可以这样做:

declare module "*.png" {
  const value: any;
  export default value;
}

更新

类型检查的最佳解决方案是:

declare module "*.png" {
   const value: any;
   export = value;
}

41
投票

对于

react-native

在项目

global.d.ts
文件夹中创建
root
文件,然后在其中添加下一行

declare module '*.png' {
  const value: import('react-native').ImageSourcePropType;
  export default value;
}

5
投票

我创建了index.d.ts并添加了“声明模块“*.jpg””,它不起作用,但是当我将名称更改为custom.d.ts(或任何其他名称)时,它工作正常。


2
投票

就我而言,即使配置了 global.d.ts,由于导入它也无法工作。而不是

从“assets/images/logo.png”导入 * 作为徽标;

我用过:

从“assets/images/logo.png”导入图像;

效果很好。

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