gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:09:16 25 4
gpt4 key购买 nike

我被卡住了,无法使用我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com