javascript - webpack 4 给出背景: url([object Module]) as bg image
问题描述
我在设置 web-pack 4 和 svg-sprite-loader 以将 svg 图标呈现为背景图像时遇到问题。我按照 svg-sprite-loader 的官方文档(https://github.com/kisenka/svg-sprite-loader/tree/master/examples/extract-mode)的这些说明进行操作。
我已经成功地在我的 dist 文件夹中创建了 sprite.svg 文件,并将其用作我在 html 中的 use 标签的参考。但是,我也尝试使用 src/images/icons 文件夹中的 svg 图标作为背景图像,如下所示:
background: url('../images/icons/upload_icon.svg') 10% 50% no-repeat;
这样做时,webpack 会正确编译,但会在 dist css 文件中创建它:
background: url([object Module]) 10% 50% no-repeat;
任何帮助都会很棒。
这是我的 webpack 配置文件:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const SpriteLoaderPlugin = require("svg-sprite-loader/plugin");
module.exports = {
mode: "development",
devtool: "source-map",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
sourceMap: true
}
}
},
{
// scss configuration
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader"
},
{
loader: "postcss-loader"
},
{
loader: "sass-loader",
options: {
sourceMap: true
}
}
]
},
{
// html configuration
test: /\.html$/,
use: {
loader: "html-loader"
}
},
{
// images configuration
test: /\.(jpg|jpeg|gif|png|woff|woff2)$/,
use: [
{
loader: "file-loader",
options: {
name: "[path][name].[ext]"
}
}
]
},
{
test: /\.svg$/,
use: [
{
loader: "svg-sprite-loader",
options: {
extract: true,
spriteFilename: "sprite.svg"
}
}
]
}
]
},
plugins: [
// all plugins used for compiling by webpack
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Style Guide",
template: path.resolve(__dirname, "src", "index.html")
}),
new MiniCssExtractPlugin({
filename: "app.css"
}),
new SpriteLoaderPlugin()
]
};
解决方案
添加esModule: false
到文件加载器选项对我有用。
{
test: /\.(jpg|png|gif|svg)$/,
use: {
loader: 'file-loader',
options: {
name: "[name].[ext]",
outputPath: "img",
esModule: false
}
},
推荐阅读
- android - MVVM - 如何跨多个 ViewModel 共享单个存储库类
- android - 如果异步任务被解除,则重新显示进度对话框
- java - SQLite 数据库未更新
- mysql - 远程连接到 MySQL 数据库的问题(错误 1045)
- c# - 在网络编程中如何最好地处理图像和泛型类型
- php - 在 Laravel ui auth forgot password 表单中更改输入名称
- java - 带有片段的空指针异常 - 尝试调用虚拟方法“void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)”
- c - gdb 运行程序后自动退出
- r - 删除字符串中的游程重复数字和 NA
- android - 使用 Fetch 库 Android 为组下载显示单个 ProgressBar