如何使用 webpack 4 简单地加载带有 src 属性的图像?

Vik*_*sIT 5 html javascript webpack webpack-4

我卡住了,无法使用我的 webpack 配置从 HTML 加载带有 src 属性的图像。我克隆了一个完整设置 webpack 的 repo,但我知道有一种方法可以直接从 HTML 自定义和加载图像。

Webpack.config.js 文件:

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"
}),
Run Code Online (Sandbox Code Playgroud)

在这个项目之前,我能够使图像简单地从 HTML 加载,但具有讽刺意味的是,我现在卡住了,无法正常工作。

任何帮助将非常appriciated。

直接从 HTML 加载图像时,出现以下错误:

 Error: Child compilation failed:
 Module not found: Error: Can't resolve ' 
 ./src/assets/images/portret.jpg' in '/home/viktoras/www/sites/painter-new/src':
Run Code Online (Sandbox Code Playgroud)

小智 1

你可以这样做:

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

    Plugin Conf
    $new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html'
      }),
Run Code Online (Sandbox Code Playgroud)