【问题标题】:Webpack won't load background-image into html fileWebpack 不会将背景图像加载到 html 文件中
【发布时间】:2021-04-21 05:43:12
【问题描述】:

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

// 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,
    },
};


【问题讨论】:

    标签: javascript webpack sass wsl-2


    【解决方案1】:

    我认为您使用的是 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,也许有些代码对你有用。

    【讨论】:

      【解决方案2】:

      你能用url-loader试试吗,它对我很好。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-25
        • 2016-11-25
        • 2016-12-14
        • 1970-01-01
        • 1970-01-01
        • 2021-10-05
        • 2019-05-04
        • 2012-07-11
        相关资源
        最近更新 更多