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

标签 javascript html webpack webpack-4

我被卡住了,无法使用我的 webpack 配置来从 HTML 加载具有 src 属性的图像。我克隆了一个具有 webpack 完整设置的存储库,但我知道有一种方法可以简单地自定义并直接从 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"
}),

在这个项目之前,我能够简单地从 HTML 加载图像,但讽刺的是,现在我陷入困境,无法正常工作。

任何帮助将非常感激。

直接从 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':

最佳答案

你可以这样做:

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

    Plugin Conf
    $new HtmlWebpackPlugin({
        filename: 'index.html',
        template: 'index.html'
      }),

关于javascript - 如何使用 webpack 4 简单地加载具有 src 属性的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60302749/

相关文章:

javascript - CodePen javascript 代码在本地不起作用

javascript - 如何在页面中注入(inject)的函数表达式中使用变量?

javascript - 表头和表体列不匹配

javascript - 在 ES6 中有条件导入模块

javascript - useRef typescript 错误 : Property 'current' does not exist on type 'HTMLElement'

html - Iconfont 显示和悬停

JavaScript 手机交换

node.js - Webpack 需要字符串替换

javascript - Nuxt.js + vuetify 图像未加载

javascript - 多个下拉选择列表中的最小值,例如 math.min