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...
@types/webpack-env
instead and fall backrequire
instead ofimport
. Unlike import, the string you pass torequire
doesn't get resolved by TypeScript. Of course, using a*.d.ts
is fine, too – Haemostasis@types/webpack-env
, whilst I've used@types/node
. The node types do work. What is the difference between these two, in terms of getting 'require' to work? I assume they are simply two d.ts definitions of the same underlying 'require' implementation? – Morisco@types/webpack-env
and@types/node
are different, you use@types/node
when you need to write NodeJS modules to make standard library typings available.@types/webpack-env
is used when you are in a webpack bundled project. For instance,require.ensure
will be available if you use@types/webpack-env
– Haemostasis@types/webpack-env
. – Moriscoexport default
to have typestring
in this case – Haemostasis