javascript - 为什么我不能在带有 HTML img 标签的 webpack 中嵌入图像?
问题描述
为什么我不能在带有 HTML img 标签的 webpack 中嵌入图像?
下面是 webpack.config.js 的内容。
// webpack.config.js
const {
CleanWebpackPlugin,
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = [{
mode: 'development',
entry: {
'px.bundle': ['./src/index.js'],
},
output: {
path: path.resolve(__dirname,'dist'),
filename: '[name].js'
},
module:{
rules:[
{
test:/\.css$/,
use:[
'style-loader',
'css-loader'
]
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
}
]
},
devServer: {
static : {
directory: path.join(__dirname, 'public'),
},
compress: true,
port: 9000
},
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: ["**/*", "!assets/**/*", "!resources/**/*"],
}),
new MiniCssExtractPlugin({
filename: 'style.css',
}),
new HtmlWebpackPlugin({
title: 'Project Demo',
minify: {
collapseWhitespace: true
},
hash: true,
template: './src/index.html'
}),
],
performance: {
hints: false,
maxEntrypointSize: 512000,
maxAssetSize: 512000,
},
}, {
mode: 'product',
entry: {
'px.bundle': ['./src/index.js'],
},
output: {
path: path.resolve(__dirname,'dist'),
filename: '[name].js',
},
module:{
rules:[
{
test:/\.css$/,
use:['style-loader','css-loader']
}
]
},
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: ["**/*", "!assets/**"],
cleanOnceBeforeBuildPatterns: ["**/*", "!resources/**"],
cleanAfterEveryBuildPatterns: ['dist'],
}),
new MiniCssExtractPlugin({
filename: 'style.css',
}),
new HtmlWebpackPlugin({
title: 'Project Demo',
minify: {
collapseWhitespace: true
},
hash: true,
template: './src/index.html'
}),
],
performance: {
hints: false,
maxEntrypointSize: 512000,
maxAssetSize: 512000,
},
},
];
下面是包含 index.html 内容的代码。
<img class="header__logo" src="img/ico_logo.png" alt="company logo" />
如果像这样输入 npm run dev 命令,img/ico_logo.png 的内容将无法正常输出。当然,我检查了文件是否正确位于路径中。
将上面的代码更改为以下内容,
<img class="header__logo" alt="company logo" />
如果我在我的 CSS 中包含以下内容
.header__logo{
content:url('../img/ico_logo.png')
}
如果输入 npm run dev 命令,我可以看到它工作正常。
如果在 HTML 中将 src 指定为 img 标签,webpack 不能包含图像。不知道是不是webpack设置错了,还是webpack只能通过css中的url才能正常工作。
我想知道是否由于某种原因 webpack 没有正确嵌入徽标图像,我该如何解决?
解决方案
你可以试试这个
{
test: /\.(jpg|jpeg|png|gif|pdf|ico)$/,
use: [
{
loader: "file-loader",
options: {
name: "images/[name].[ext]",
},
},
],
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: {
minimize: true,
},
},
],
},
推荐阅读
- javascript - 喜欢和不喜欢 Reat Js
- rxjs - 如何在一个承诺中加载一个包含所有子集合的 firebase-collection?
- python - 使用 python 在网络抓取中获取标签的内容而不获取其子项的内容
- css - 如何创建 1 列始终居中的 3 列 flexbox 容器?
- plugins - ansible受管节点无法查看文件内容
- python - 如何将 SVG 提供给 Flask 网站
- javascript - MongoDB 嵌套组聚合
- typescript - Storybook 不支持 vuetify 的 v-calendar
- c# - 在 Solr 中向 RequestHandler 添加组件字符串(有或没有 SolrNet)
- printing - 如何打印没有白条的 Beamer 演示文稿?