Webpack & Typescript Image Import

I am working on a React application and use Webpack and Typescript . I would like to use the image in one of the <img/> tags. However, I did not find a suitable way to access image files.

webpack.config.js

  ... module: { rules: [ ... { test: /\.(png|jpe?g|svg)$/, loader: 'file-loader', options: { name: 'assets/[name].[ext]', } } ] 

app.tsx

 ... render() { return <img src='/assets/logo-large.png' alt="logo"/> } 

When starting the application, the asset assets/logo-large.png not found.

+5
source share
2 answers

You need to require image, and then use this variable as a source, for example:

 // At the top of the file, with all other imports/requires const imageSrc = require('/assets/logo-large.png') ... render() { return <img src={imageSrc} alt="logo"/> } 
+6
source

In addition, in your custom_typings folder (if any) you can add a new import-png.d.ts :

declare module "*.png" { const value: string; export default value; }

So you can import the image using:

import myImg from 'img/myImg.png';

+2
source

Source: https://habr.com/ru/post/1267193/


All Articles