Displaying a static image using React, Typescript and Webpack

Montgomery 'monty' Jones picture Montgomery 'monty' Jones · Jun 1, 2017 · Viewed 27.6k times · Source

I'm attempting to display an image in a React component as part of a project using webpack and webpack-dev-server.

So far I have completed the following steps:

  • Used npm to install file-loader
  • Updated webpack.config.js to add a loader for image files
  • Imported the image I want into my component
  • Used the import in my img tag

Having taken these steps, webpack fails to compile with a 'cannot find module' error:

ERROR in [at-loader] ./src/components/App.tsx:4:26
    TS2307: Cannot find module '../images/kitten-header.jpg'.

My folder structure is as follows:

/dist
   /images
      kitten-header.jpg
   bundle.js
   bundle.js.map
/node_modules
   (content ignored for brevity)
/src
   /components
      App.tsx
   /images
      kitten-header.jpg
   /styles
      App.less
   index.tsx
index.html
package.json
tsconfig.json
webpack.config.js 

The new loader that I added to my webpack.config.js is:

test: /\.(jpe?g|gif|png|svg)$/, loader: "file-loader?name=./images/[name].[ext]"

I've imported the image file, in App.tsx, like this:

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

...and used the import in an img tag like this:

<img src={ kittenHeader } />

Note: Full text of webpack.config.js and App.tsx were provided until I got a little bit closer to the answer and realized they weren't relevant (see update 1).

I assume I'm making some very trivial error with regards to the relative path in the import. As you can imagine, I've tried various alternatives.

Can anyone provide some insight?

For reference, as I'm continuously hitting articles and questions relating to the wrong version of webpack, here are my versions:

  • React 15.5.4
  • Webpack 2.6.1
  • Webpack-dev-server 2.4.5
  • TypeScript 2.3.2


Update 1: 2017.06.05
So, looking at this SO question and this post on Medium, I've been able to identify that the problem lies not with how I've used webpack, but with that fact that I'm using TypeScript. The error is a typescript error caused by the fact that the typescript compiler doesn't know what a .jpg file is.

Apparently, I'm going to need to provide a d.ts file or use a require statement.

Almost there...

Answer

mcku picture mcku · Oct 1, 2017

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.