reactjs - 打字稿图像导入
问题描述
我在这里找到了一个解决方案: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"]
}
解决方案
消除该错误的方法之一是修改 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;
}
推荐阅读
- typescript - 为什么我们应该使用“extends”关键字而不是类型本身?
- javascript - 如何在页面上的两个 DataTable 之间切换?
- android - 数据库不更新值
- python - 如何在 Matplotlib 中使用 bin 作为我的 xticks?
- google-cloud-platform - 无法在 Google 云配额编辑屏幕上选择要编辑的配额
- docker - 使用 Terraform 和 Kubernetes 部署时如何修改 Docker 容器中的文件?
- c++ - 调用函数一次
- css - 向右对齐元素没有重叠的问题
- r - 对齐 x 轴标签以与 R 中的 x 轴对齐
- python - 数据框:创建新的数据框,在多列的基础上保持重复超过 2 次(时间限制)