Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simply load images with src attribute with webpack 4?

Im stuck and can't get to work my webpack configuration for loading images with src attribute from HTML. I cloned a repo with full setup of webpack, but I know there is a way to simply customize and load images directly from HTML.

Webpack.config.js file:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
entry: {
main: "./src/index.js"
},
output: {
path: path.join(__dirname, "../build"),
filename: "[name].bundle.js"
},
mode: "development",
devServer: {
contentBase: path.join(__dirname, "../build"),
compress: true,
port: 3000,
overlay: true
},
devtool: "cheap-module-eval-source-map",
module: {
 rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
      loader: "babel-loader" // transpiling our JavaScript files using Babel and webpack
    }
  },
  {
    test: /\.(sa|sc|c)ss$/,
    use: [
      "style-loader", // creates style nodes from JS strings
      "css-loader", // translates CSS into CommonJS
      "postcss-loader", // Loader for webpack to process CSS with PostCSS
      "sass-loader" // compiles Sass to CSS, using Node Sass by default
    ]
  },
  {
    test: /\.(png|svg|jpe?g|gif)$/,
    use: [
      {
        loader: "file-loader", // This will resolves import/require() on a file into a url 
and emits the file into the output directory.
        options: {
          name: "[name].[ext]",
          outputPath: "assets",
        }
      },
    ]
  },
  {
    test: /\.html$/,
    use: {
      loader: "html-loader",
      options: {
        attrs: ["img:src", ":data-src"],
        minimize: true
      }
    }
  }
]
},

plugins: [
  // CleanWebpackPlugin will do some clean up/remove folder before build
  // In this case, this plugin will remove 'dist' and 'build' folder before re-build again
  new CleanWebpackPlugin(),
  // The plugin will generate an HTML5 file for you that includes all your webpack bundles 
in 
the body using script tags
new HtmlWebpackPlugin({
  template: "./src/index.html",
  filename: "index.html"
}),

Before this project I was able to make that images would simply load from HTML but now ironicly im stuck and can't get this working.

Any help will be very appriciated.

When loading a image directly form HTML, I get the following error:

 Error: Child compilation failed:
 Module not found: Error: Can't resolve ' 
 ./src/assets/images/portret.jpg' in '/home/viktoras/www/sites/painter-new/src':
like image 696
ViktorasssIT Avatar asked Nov 07 '22 09:11

ViktorasssIT


1 Answers

You can do this:

<img src="<%=require('./src/assets/logo.png')%>">

    Plugin Conf
    $new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html'
      }),
like image 192
Elimane Sene Avatar answered Nov 14 '22 22:11

Elimane Sene