我在这里找到了解决方案: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,这就是为什么会弹出错误。
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"] }
摆脱该错误的一种方法是通过按如下方式修改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; }