Search code examples
imagewebpackloader

Loading local images with webpack


Hi I am trying to load local images with webpack, it compiles successfully however I get the following error (and no image)

GET http://192.168.1.196:3000/b09d0fa90cacadcad6ce1679aea3d2ee.png 404 (Not Found)

Here is my webpack.config.js file:

    const path = require('path')

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'public/scripts'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env']
                }
            }
            },
            { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }

        ]
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'public'),
        publicPath: '/scripts/'
    },
    devtool: 'source-map'
}

Here is how I am importing the image

import goku from '../public/images/goku.png'

I am trying also with require in the img directly with the same result.

<img src =${require('../public/images/goku.png')}>
<img src =${goku}> 

Solution

  • Your problem is actually that you missed a publicPath on output:

    output: {
            path: path.resolve(__dirname, 'public/scripts'),
            filename: 'bundle.js',
            publicPath: '/scripts/'
        },
        devServer: {
            contentBase: path.resolve(__dirname, 'public'),
            publicPath: '/scripts/'
        },
    

    The property publicPath on output has to match the publicPath on devServer.