[英]Why can't I embed images in webpack with HTML img tags?
為什么我不能在帶有 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的內容就不是output了。 當然,我檢查了文件是否正確位於路徑中。
將上面的代碼改成如下, <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 沒有正確嵌入徽標圖像,我該如何解決?
我認為原因是 webpack 無法讀取 HTML,盡管您使用了 HtmlWebpackPlugin。 它只是幫助您將 HTML 提取到文件中,但看起來它沒有讀取內容。 我有同樣的問題,但我通過添加 use html-loader解決了它。 我在規則中增加了一個新的 object。
,{
test: /\.html$/i,
loader: 'html-loader'
}
它有效。 此外,文件加載器已被 webpack 中的資產模塊取代 5. 真誠地希望這對您有所幫助。
你可以試試這個
{
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,
},
},
],
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.