Displaying a static image using React, Typescript and Webpack

穿精又带淫゛_ 提交于 2019-12-05 08:10:37

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 error
declare 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.

In addition to mcku's answer you can also use imports this way:

// @ts-ignore
import * as kittenHeader from '../images/kitten-header.jpg';
...
<img alt='logo' style={{ width: 100 }} src={logo} />

Although you have to ignore the warning.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!