gpt4 book ai didi

Webpack 5 如何在 HTML 文件中显示图像

转载 作者:行者123 更新时间:2023-12-05 02:42:37 24 4
gpt4 key购买 nike

我将 webpack 用于一个小型应用程序,到目前为止它运行良好,除了我在显示图像时遇到问题 - 我收到 404。

这是我的 webpack 配置:

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 2, sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { implementation: require('sass'), sourceMap: true } },
]
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'src/assets/images'
}
},
],
},
{
test: /\.js$/i,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
{
// Extract any CSS content and minimize
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{ loader: 'postcss-loader' }
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './dist/index.html',
inject: 'body',
chunks: ['index'],
filename: 'index.html'
}),
new MiniCssExtractPlugin({
filename: 'src/css/[name].min.css'
}),
],
devServer: {
watchContentBase: true,
contentBase: path.resolve(__dirname, 'dist'),
open: true
}
};

然后在我的 index.html 中,我尝试这样做:

<img class="object-cover z-0 w-full h-full" src='/src/assets/images/top_image.png'>

但就像我之前提到的,我得到 404...

有人可以帮帮我吗?

最佳答案

您需要更改您的遗留 Assets 加载器...对于图像,建议使用asset/resource

使用 asset/resource 代替 file-loader。像这样的东西:

编辑你的规则:

{
test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
type: 'asset/resource'
}

并在您的 webpack.output 中添加:

output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
assetModuleFilename: 'src/assets/images/[name].[ext]'
}

您可以在 Webpack assets loader guide 上查看更多详细信息

关于Webpack 5 如何在 HTML 文件中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67432536/

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