I found a solution here: Webpack & Typescript image import
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 can't figure out how.
I am doing this in React. I saw that src
attribute is defined as string | undefined
, that is why error is popping.
Here is code:
import * as Logo from 'assets/images/logo.png';
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"]
}
const Logo = require('assets/images/logo.png')
– Giagiacamoimport
it works when you load app. But you get lint error. – Klanimport
works so it should be used. @MarioPetrovic a default import has no name. That is why you can leave out the* as
part.import Logo from './logo.jpg'
is fine because it's equivalent toconst Logo = require(./logo.jpg)
– Killie<img src={require('assets/images/logo.png')} />
works. What makes it not elegant, if you only need to reference it in that one line? To me, it feels more elegant and bulletproof than modifyingd.ts
files. – Exothermicd.ts
and use it later in your project it makes it more organic and consistent with regular importing. – Klan