Ly Maneug Ly Maneug - 1 year ago 219
HTML Question

ReactJS + Webpack: Why Uncaught Error: Cannot find module "../media/interiorTest.jpg"?

I have a Webpack running with ReactJS, and I am attempting to grab an image and display it but getting an error:

Uncaught Error: Cannot find module "../media/interiorTest.jpg"

And here is what I tried:

<img src={require("../media/interiorTest.jpg")}/>

And the directory tree is (I am trying to fetch

enter image description here

And my

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const config = {
context: __dirname,
entry: './src/index.js',
output: {
path: __dirname,
filename: 'bundle.js'
module: {
loaders: [
exclude: /node_modules/,
test: /\.(js|jsx)$/,
loader: 'babel'
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
devServer: {
historyApiFallback: true,
contentBase: './'
plugins: [
new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify('production') } }),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
output: {comments: false },
mangle: false,
sourcemap: false,
minimize: true,
mangle: { except: ['$super', '$', 'exports', 'require', '$q', '$ocLazyLoad'] }
new ExtractTextPlugin('src/public/stylesheets/app.css', {
allChunks: true

module.exports = config;

Answer Source

By looking at the code in webpack.config.js and the screenshot you included, Your directory structure looks like


And in webpack.config.js you have this code

  devServer: {
    historyApiFallback: true,
    contentBase: './'

contentBase property defines the directory from where files will be loaded when the server is running, And since you have set it as './', It means the files/data will be loaded from the app directory.

And that's the reason to link files from public directory you have to include /src/public in path as well, something like src="/src/public/folder/where/image/is-located/image.jpg"

In this case

    <img src="/src/public/media/interiorTest.jpg" alt="" />


  • Usually the code is divided into two folders, src to store the code you're working on and public for webpack to store the compiled code and for static assets. And we just set /public as the contentBase.

    It will be worth your time to do some research regarding directory structure for react and javascript applications

  • Its good to have alt="" for images, Just enter the alt text as it best describes the image.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download