I am not able to import images in my headercomponent.ts. I suspect it is because of something i am doing wrong while compiling ts(using webpack ts loader) because same thin
A small improvement to Christian Stornowski's answer would be to make the export default, i.e.
declare module "*.png" {
const value: string;
export default value;
}
So you can import an image using:
import myImg from 'img/myImg.png';
To be able to use default import like this:
import grumpyCat from '../assets/grumpy_cat.jpg';
Define jpg
module declaration:
declare module "*.jpg" {
const value: string;
export default value;
}
and in your tsconfig
use "module": "es6"
(see @vedran comment above) or when you use "module": "commonjs"
add "esModuleInterop": true,
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"esModuleInterop": true,
...
Source: https://github.com/TypeStrong/ts-loader/issues/344#issuecomment-381398818
I also had same issue so I used following approach:
import * as myImage from 'path/of/my/image';
In my component I simply assigned the imported image to a data member;
export class TempComponent{
public tempImage = myImage;
}
and used it in template as:
<img [src]="tempImage" alt="blah blah blah">
I'm using
import * as myImage from 'path/of/my/image.png';
and created a typescript definition with
declare module "*.png" {
const value: any;
export = value;
}
This only works when you have a correct handler like the file-loader in webpack. Because this handler will give you a path to your file.
Instead of:
import image from 'pathToImage/image.extension';
Use:
const image = require('pathToImage/image.extension');
The problem is that you confuse TypeScript level modules and Webpack level modules.
In Webpack any file that you import goes through some build pipeline.
In Typescript only .ts
and .js
files are relevant and if you try to import x from file.png
TypeScript just does not know what to do with it, Webpack config is not used by TypeScript.
In your case you need to separate the concerns, use import from
for TypeScript/EcmaScript code and use require
for Webpack specifics.
You would need to make TypeScript ignore this special Webpack require
syntax with a definition like this in a .d.ts
file:
declare function require(string): string;
This will make TypeScript ignore the require statements and Webpack will be able to process it in the build pipeline.