我在这里找到了一个解决方案: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;
}
配置:
{
"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"]
}