首页 > 解决方案 > 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()
  ]
};

标签: javascriptwebpackwebpack-4svg-sprite

解决方案


添加esModule: false到文件加载器选项对我有用。

{
    test: /\.(jpg|png|gif|svg)$/,
    use: {
        loader: 'file-loader',
        options: {
            name: "[name].[ext]",
            outputPath: "img",
            esModule: false
    }
},

推荐阅读