Displaying a static image using React, Typescript and Webpack Displaying a static image using React, Typescript and Webpack reactjs reactjs

Displaying a static image using React, Typescript and Webpack


With regular require, this is how I use it in a tsx file:

const logo = require('../assets/logo.png');...<img alt='logo' style={{ width: 100 }} src={String(logo)} />

Hope this helps. importing did not work for me, either.


This is how I get it working:

// This declaration can be move in some common .d.ts file, will prevent tslint from throwing errordeclare function require(path: string);const SampleComponent = () => (  <div>    <img src={require('./styles/images/deadline.png')} alt="Test" />  </div>);

The way you proposed in your answer will end up writing modules declaration for each image file being placed in components.


The error, TS2307: Cannot find module '../images/kitten-header.jpg', is highlighting that the TypeScript compiler does not understand the import of a .jpg file.

The webpack configuration is fine, as evidenced by the image file being copied to the dist folder successfully despite the compile error.

There are two ways that we can resolve the issue.

Firstly, we could bypass the TypeScript import by using a 'require' statement. To do this, the import...

import kittenHeader from '../images/kitten-header.jpg';

...can be replaced with a require...

const kittenHeader = require('../images/kitten-header.jpg');

...and that should be all that's needed.

Note that, in my case I also needed to install some typings to support the 'require' statement. Without these, I was getting a TS2304: Cannot find name 'require' error.

Originally I used @types/node, as described in this SO answer, but @EvanSebastian pointed out that node is intended to support writing NodeJS modules, which is not what I'm doing (see comments on the question).

I tried @types/webpack-env, as suggested, but this resulted in a TS2322: Type '{ src: {}; }' is not assignable to type 'HTMLProps<HTMLImageElement>'. error against the src property of my image tag.

Most recently, I've switched to using @types/requirejs, which I'm hoping is focused enough to avoid including a load of inappropriate additional types. It is currently working:

npm install @types/requirejs --save-dev

Alternatively, we could keep the import and provide a d.ts file with type information declaring an appropriate module. I've not been able to discover exactly what this file would look like.