在我的 scss 檔案中,我使用 background-image: url("../../../assets/images/home/banner-mobile.png");
應用程式運行成功,但沒有顯示背景影像:
背景圖片網址無法決議。

webpack/webpack.base.js
const webpack = require("webpack");
const path = require("path");
const utils = require("./utils");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.jsx",
resolve: {
alias: {
"@": utils.resolve("src")
},
extensions: ["*", ".js", ".jsx"],
fallback: {...},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
},
{
loader: "sass-loader"
},
{
loader: "sass-resources-loader",
options: {
resources: ["./src/assets/scss/main.scss"],
},
},
],
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: "url-loader",
options: {
limit: 8192
},
},
],
}
],
},
plugins: [
new HtmlWebpackPlugin({
template: "public/index.html",
filename: "index.html",
inject: true,
})
],
};
webpack/webpack.dev.js
const { merge } = require("webpack-merge");
const base = require("./webpack.base");
const Dotenv = require("dotenv-webpack");
module.exports = merge(base, {
mode: "development",
devtool: "inline-source-map",
output: {
publicPath: '/',
},
devServer: {
port: 3000,
static: true,
static: 'dist'
},
plugins: [new Dotenv({ path: "./.env.development" })],
});
更新 1
當我在 Web Inspector > Sources 中查看 png 時:

當我在瀏覽器中通過其 url 打開影像時:

更新 2:
當我通過 VSCode 構建和查看影像時,它顯示如下:

不確定以下檔案是否相關
網路包/Util.js
const path = require('path')
module.exports = {
resolve: function(dir) {
return path.join(__dirname, '..', dir)
}
}
uj5u.com熱心網友回復:
由于您使用的是 Webpack 5,我建議您使用Asset Modules而不是已棄用的加載器
module: {
rules: [
// ...
{
test: /\.(png|jpg|gif)$/i,
type: "asset",
parser: {
dataUrlCondition: {
maxSize: 8192
}
}
}
]
}
我懷疑您遇到了檔案中所述的資源處理重復問題...
當使用舊資產裝載機(即
file-loader/url-loader/raw-loader)與資產模塊沿的WebPack 5,你可能想再次處理您的資產將導致資產重復停止資產模塊。這可以通過將資產的模塊型別設定為'javascript/auto'.
uj5u.com熱心網友回復:
我使用檔案加載器,如本規則所示,它允許我保留檔案名和相對路徑,因此我的檔案夾結構如資產 > 影像,我只需要從路徑中洗掉“資產”:
{
test: /\.(gif|png|jpg|jpeg)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: (file) => {
const p = file.split('assets/')[1];
return p;
},
},
},
這將使您將“assets”檔案夾中的所有影像直接放入根包中,并且每個路徑都將被復制(例如,assets/images/home/banner.png 將位于 dist 目錄中的 images/home/banner.png 上) ,只需確保您的所有影像都在您的資產檔案夾中,以避免名稱沖突
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368944.html
標籤:javascript 反应 蠢货 webpack-5 网址加载器
