typescript 打字稿图像导入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51100401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:54:40  来源:igfitidea点击:

Typescript image import

reactjstypescriptmoduletsconfigreact-tsx

提问by Mario Petrovic

I found a solution here: Webpack & Typescript image import

我在这里找到了一个解决方案:Webpack & Typescript image import

But i am getting error for this:

但我收到错误:

[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'.

I guess i need to cast import somehow, but cant figure out how. I am doing this in React. I saw that srcattribute is defined as string | undefined, that is why error is popping.

我想我需要以某种方式导入导入,但无法弄清楚如何。我正在 React 中执行此操作。我看到该src属性被定义为string | undefined,这就是错误弹出的原因。

Here is code:

这是代码:

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

HTML:

HTML:

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

And definition based on above mentioned solution:

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

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"]
}

回答by Piyush Zalani

One of the ways to get rid of that error is by modifying d.ts file as follows:

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

declare module "*.png"

remove

消除

{
  const value: string;
  export default value;
}

or alternatively you can do:

或者你可以这样做:

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

Update

更新

The best solution with type-checking is:

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

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