简体   繁体   中英

images not loading in html using webpack

I'm having any issue loading images from a different folder than where my index.html file is located. Below is the message I am getting from the console.

GET http://localhost:3000/company-logo.jpg 404 (Not Found)

Here is my file directory

在此处输入图像描述

webpack.config.js

const currentTask = process.env.npm_lifecycle_event
const path = require('path')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const fse = require('fs-extra')

const postCSSPlugins = [
    require('postcss-import'),
    require('postcss-simple-vars'),
    require('postcss-nested'),
    require('autoprefixer')
]

class RunAfterComile {
    apply(compiler) {
        compiler.hooks.done.tap('Copy images', function() {
            fse.copySync('./public/images', './dist/public/images')
        })
    }
}

let cssConfig = {
    test: /\.css$/i,
    use: ['css-loader?url=false', {loader: 'postcss-loader', options: {plugins: postCSSPlugins}}]
}

let pages = fse.readdirSync('./views').filter(function(file) {
    return file.endsWith('.html')
}).map(function(page) {
    return new HtmlWebpackPlugin({
        filename: page,
        template: `./views/${page}`
    })
})

let config = {
    entry: './public/scripts/App.js',
    plugins: pages,
    module: {
        rules: [
            cssConfig
        ]
    }
}

if (currentTask == 'dev') {
    cssConfig.use.unshift('style-loader')
    config.output = {
        filename: 'bundled.js',
        path: path.resolve(__dirname, 'public')
    }
    config.devServer = {
        before: function(app, server) {
            server._watch('./views/**/*.html')
        },
        contentBase: path.join(__dirname, './views'),
        hot: true,
        port: 3000
    }
    config.mode = 'development'
}

if (currentTask == 'build') {
    config.module.rules.push({
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
            loader: 'babel-loader',
            options: {
                presets: ['@babel/preset-env']
            }
        }
    })
    cssConfig.use.unshift(MiniCssExtractPlugin.loader)
    postCSSPlugins.push(require('cssnano'))
    config.output = {
        filename: '[name].[chunkhash].js',
        chunkFilename: '[name].[chunkhash].js',
        path: path.resolve(__dirname, 'dist')
    }
    config.mode = 'production'
    config.optimization = {
        splitChunks: {chunks: 'all'}
    }
    config.plugins.push(
        new CleanWebpackPlugin(), 
        new MiniCssExtractPlugin({filename: 'styles.[chunkhash].css'}),
        new RunAfterComile()
        )
}

module.exports = config

The css works perfectly fine. I seem to only be having problems with images.

I tried the following file paths but they didn't work. I think I am missing something.

index.html

  1. <img src="./company-logo.jpg" alt="dfgadfg">
  2. <img src="../public/images/company-logo.jpg" alt="dfgadfg">
  3. <img src="./images/company-logo.jpg" alt="dfgadfg">

any help would be appreciated. Thank you very much.

Try use

module: {
      rules: [
       {
         test: /\.(png|svg|jpg|gif)$/,
         use: [
           'file-loader',
         ],
       },
      ],
    },

You might require file-loder to get the images correctly served

rules: [
  {
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
      outputPath: 'images' // Chage this like 'public/images' or any other relative path to the root
    }
  },
  ...
]

Try to inspect and check how the images are loading in Source tab of Developer Tools , change the outputPath accordingly.

Update

If images are still not loading to Source tab of browser, try importing it in your App.js (Entry point file)

....
import "../public/images/company-logo.jpg";

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM