displaying broken image - using webpack 4

494 Views Asked by At

I'm self-taught coder and new to Webpack(v.4). I'm trying to display some images from a file, but they display broken in all browsers. I installed a file-loader, and even tried a direct url link after installing a url-loader, but no luck. I'm not sure what I'm missing. Any guidance would be greatly appreciated.

This is my file structure:

This is the dev.js file:

const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin')

module.exports = {
    entry: './src/client/index.js',
    mode: 'development',
    devtool: 'source-map',
    output: {
        libraryTarget: 'var',
        library: 'Client'
    },
    stats: 'verbose',
    module: {
        rules: [{
                test: '/\.js$/',
                exclude: /node_modules/,
                loader: "babel-loader"
            },
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            },
            {
                test: /\.jpg$/,
                loader: 'file-loader'
            },
            {
                test: /\.(jpeg|png|jpg|JPG|gif)$/,
                loader: 'url-loader',
            }
            
        ]
    }, 

This is my index.js file:

import {
  checkForUrl
} from './js/urlChecker'
import {
  handleSubmit
} from './js/formHandler'

import './styles/resets.scss'
import './styles/base.scss'
import './styles/form.scss'
import './styles/footer.scss'
import './styles/header.scss'
import './images/negative.jpg'
import './images/neutral.jpg'
import './images/positive.jpg'


console.log(checkForUrl);

export {
  checkForUrl,
  handleSubmit
}

And here is how I'm using it in my function- maybe this is not correct

.then(function (res) {
            if(res.polarity === 'neutral') {
                let img = document.createElement('img');
                img.src = './images/neutral.jpg'
                document.getElementById('polarityImg').appendChild(img);
            }
            if(res.polarity === 'positive'){
                let img = document.createElement('img');
                img.src = './images/positive.jpg'
                document.getElementById('polarityImg').appendChild(img);
            }
            if(res.polarity === 'negative'){
                let img = document.createElement('img');
                img.src = './images/negative.jpg'
                document.getElementById('polarityImg').appendChild(img);
            }

Thank you in advance for helping a noob like me!

1

There are 1 best solutions below

0
Dom On

You should import your image using either the CJS or ES6 Modules syntax as shown in the Webpack documentation. Please refer to https://webpack.js.org/guides/asset-management/#loading-images this section of the webpack documentation for further guidance!