webpack - Webpack 5 如何在 HTML 文件中显示图像
问题描述
我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 ......
有人可以帮我吗?
解决方案
您需要更改旧资产加载器...对于图像,建议使用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]'
}
推荐阅读
- python - 如何计算整数的各个数字的总和并在最后打印原始整数?
- python - “元组”对象在 python、jupyter 中不可调用
- azure-devops - 用于 azure devops 的 chrome 中的 URL/网页空白
- javascript - 无法使用 json 向 jvectormap 显示数据
- scala - Scala 运算符表示法
- reactjs - 使用 react-router 实现经过身份验证的路由
- python - 如何在scrapy中从sql(pyodbc)中读取数据
- sql - Oracle SQL 查询中的正则表达式 - 仅限数字和句点
- c++ - 是否可以在异步场景中将 c++ 堆栈对象传递给不同的线程而无需复制(但移动)
- sql - 在 python 中使用 ibm_db_dbi sql 查询时出现参数错误