【问题标题】:Resolving css background-image url with Webpack使用 Webpack 解析 css 背景图像 url
【发布时间】:2021-12-22 14:42:11
【问题描述】:

我正在使用 webpack,只是尝试将在 url 属性中指定的 background-image 应用于 html 元素。

我查看了几个线程(例如this one),但没有找到适合我的内容。

这是我的设置:

// index.js

import React from 'react'
import styles from './styles.css'

const MyComponent = () => {
  return (
    <div className={styles.container}></div>
  )
}

export default MyComponent

//styles.css

.container {
  background-image: url('../../../static/public/images/my-background.jpg');
}

// webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "dist"),
    filename: "index.bundle.js"
  },
  mode: process.env.NODE_ENV || 'development',
  resolve: { 
    modules: [path.resolve(__dirname, "src"), "node_modules"],
  },
  devServer: {
    static: path.join(__dirname, 'src')
  },
  plugins: [
    new HtmlWebpackPlugin({
        template: path.join(__dirname, "src", "index.html"),
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'static',
          to: 'static'
        }
      ]
    })
  ],
  module: {
    rules: [
        { 
            test: /\.(js|jsx)$/, 
            exclude: /node_modules/, 
            use: ["babel-loader"] 
        },
        {
            test: /\.(css)$/,
            use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(jpg|png|svg|gif)$/,
          use: ['url-loader', 'file-loader'],
        },
    ],
},
}

到达 localhost 时,我确实看到了正在解析的路径:

但是,当我尝试访问该网址时,我看到的只是一个白色的小方块......

这绝对不是图片。我确实在 ./dist/static/public/images/my-background.jpg 中找到了我的构建中存在的图像

请注意,图片尺寸较大:3842 × 2162

我认为这与 webpack 加载器配置有关,但没有完全找到如何调整它以使其在这里工作。任何帮助将不胜感激!

【问题讨论】:

  • 改用{ test: /\.(jpg|png|svg|gif)$/, type: 'asset/resource', },
  • 编辑:非常感谢。刚刚尝试使用{ test: /\.(jpg|png|svg|gif)$/, type: 'asset/resource', }, 它确实显示了图像。您能否向我解释一下为什么我需要在这里删除装载机:O 似乎我在网上看到的所有使用这些装载机的例子。 XD
  • 不客气......基本上你可能正在使用新版本的 webpack,其中不推荐使用 url-loader 和 file-loader 并引入了资产模块。我会把它放在答案中:)

标签: javascript css reactjs webpack frontend


【解决方案1】:

您可能正在使用新版本的 Webpack,其中 url-loaderfile-loader 已被弃用,Asset Modules 是替代品。

尝试使用:

{
      test: /\.(jpg|png|svg|gif)$/,
      type: 'asset/resource',
},

改为。

欲了解更多信息click here

【讨论】:

  • 对于任何在谷歌上搜索的人,我使用的是 webpack:5.62.1。非常感谢@SomoKRoceS!
猜你喜欢
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 2018-08-07
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
相关资源
最近更新 更多