我在这里找到了解决方案:Webpack & Typescript image import
但是我对此有误:
[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"]
}
答案 0 :(得分:10)
摆脱该错误的一种方法是通过如下修改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;
}