[英]Typescript image import
I found a solution here: Webpack & Typescript image import我在这里找到了解决方案: Webpack & Typescript 图片导入
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.我在 React 中这样做。 I saw that src
attribute is defined as string | undefined
我看到src
属性被定义为string | undefined
string | undefined
, that is why error is popping. 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"]
}
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;
}
I created the index.d.ts and added 'declare module "*.jpg"' it didn't work but when I changed the name to custom.d.ts (or any other name) it worked fine.我创建了 index.d.ts 并添加了'declare module "*.jpg"' 它不起作用但是当我将名称更改为 custom.d.ts(或任何其他名称)时它工作正常。
For react-native
对于react-native
create global.d.ts
file on project root
folder and just add next lines there在项目root
文件夹上创建global.d.ts
文件,然后在那里添加下一行
declare module '*.png' {
const value: import('react-native').ImageSourcePropType;
export default value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.