I am trying 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 by npm to install the file loader
- Updated webpack.config.js file to add bootloader for image files.
- Imported image that I want into my component
- Used import in my img tag
Having done these steps, the web package will not be able to compile with the error "cannot find the module":
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 bootloader that I added to my webpack.config.js file:
test: /\.(jpe?g|gif|png|svg)$/, loader: "file-loader?name=./images/[name].[ext]"
I imported the image file in App.tsx, for example:
import kittenHeader from '../images/kitten-header.jpg';
... and used the import in the img tag as follows:
<img src={ kittenHeader } />
Note. The full text of webpack.config.js and App.tsx was provided until I came close to the answer and realized that they were not relevant (see Update 1).
I assume that I am making a very trivial mistake regarding the relative import path. As you can imagine, I tried various options.
Can someone give an idea?
For reference, as I constantly come across articles and questions regarding 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
<h / "> Update 1: 2017.06.05
So, looking at this SO question and this post on Medium , I was able to determine that the problem is not how I used webpack, but that I am using TypeScript. Error - typescript error caused by the typescript compiler not knowing what a .jpg file is.
Apparently I need to provide a d.ts file or use the require statement.
Almost there ...