Webpack 不会将背景图像加载到 html 文件中

Webpack won't load background-image into html file

我正在尝试通过 scss 设置背景图像,通过 webpack 捆绑,并在浏览器中打开 html 文件。其他背景属性有效,但在加载图像时,我在控制台中得到 GET file://wsl%24/c76193e7a53ed91f170bfaedb61a2832.png net::ERR_FILE_NOT_FOUND。我觉得我的风格组织方式有问题? Webpack 找到并显然根据终端构建图像,但在到达浏览器的途中发生了一些事情。任何帮助,将不胜感激。我是 运行 WSL2,带有 Ubuntu 20.04 发行版,该项目在发行版的文件树中。

// my-project/src/style.scss

.page-head {
    display: flex;
    align-items: flex-end;
    // background:
    //  linear-gradient(
    //      64.12deg,
    //      rgba(51, 51, 51, 0.8) 34.6%,
    //      rgba(255, 255, 255, 0) 100%
    //  );
    background-image: url(./images/stagetimebanner.png);
    filter: drop-shadow(0px 4px 4px rgba(0, 0, 0, 0.1));
    color: white;
    font-weight: 300;
    height: 50vh; 
// my-project/src/index.js

import "./style.scss";
require.context("./images", true);

// my-project/webpack.config.js

const path = require("path");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
    .BundleAnalyzerPlugin;

module.exports = {
    mode: "development",
    entry: "./src/index.js",
    watch: true,
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, "dist"),
        publicPath: "/",
    },
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: [
                    "style-loader",
                    "css-loader",
                    "resolve-url-loader",
                    "sass-loader",
                ],
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                use: [
                    {
                        loader: "file-loader",
                    },
                ],
            },
        ],
    },
    plugins: [new BundleAnalyzerPlugin()],
    devServer: {
        contentBase: path.join(__dirname, "public"),
        port: 9000,
    },
};


你能用 url-loader 试一下吗,对我来说很好用。

{
    test: /\.(png|eot|otf|ttf|woff|woff2|svg)$/,
    use: [ 
          { 
              loader: 'url-loader' 
          } 
         ]
};

我认为你正在使用 webpack 5,因此你不需要再使用像“url-loader”或“file-loader”这样的加载器。阅读 assets modules。你的问题应该可以通过下面的代码解决。

css

.page-head {
  background-image: url(./images/stagetimebanner.png);
}

webpack.config.js

rules: [
  {
    test: /\.(png|jpe?g|gif)$/i,
    type: 'asset/resource',
      generator: {
        // adding a hash to the file
        filename: 'images/static/[name].[hash][ext]',
      },
  },
]

PS。看看我的 webpack-boilerplate 也许其中一些代码对你有用。