【问题标题】:Cannot resolve relative URL无法解析相对 URL
【发布时间】:2020-08-06 20:42:24
【问题描述】:

当我在 SCSS 文件中使用相对 url 时(我试图将 background-image 属性设置为本地文件),我收到以下错误:

知道怎么回事吗?

我有一个具有以下结构的项目:

public/
    dist/
    images/
        wave.png
    index.html
src/
    components/
        MyComponent.js
    app.js
styles/
    base/
    components/
        _my-component.scss
    styles.scss
webpack.config.js

MyComponent.js中我渲染<div className="bg"></div>

_my-component.scss 我有:

.bg {
    background-image: url("/images/wave.png");
}

webpack.config.js 我有:

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = (env) => {
    const isProduction = env === "production";

    return {
        entry: ["./src/app.js"],
        output: {
            path: path.join(__dirname, "public", "dist"),
            filename: "bundle.js"
        },
        module: {
            rules: [
                {
                    test: /\.js$/,
                    loader: "babel-loader",
                    exclude: /node_modules/
                },
                {
                    test: /\.s?css$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: "css-loader",
                            options: {
                                sourceMap: true
                            }
                        },
                        {
                            loader: "sass-loader",
                            options: {
                                sourceMap: true
                            }
                        }
                    ]
                }
            ]
        },
        plugins: [
            new MiniCssExtractPlugin({
                filename: "styles.css"
            })
        ],
        devtool: isProduction ? "source-map" : "inline-source-map",
        devServer: {
            contentBase: path.join(__dirname, "public"),
            historyApiFallback: true,
            publicPath: "/dist/"
        }
    };
};

【问题讨论】:

  • 你在开头少了一个点:background-image: url("./images/wave.png");
  • 我尝试更改为:"./images/wave.png""./public/images/wave.png""../public/images/wave.png" 中的任何一个,但仍然看到相同的错误

标签: css reactjs webpack sass


【解决方案1】:

_my-component.scss 中,目录仅与此文件相关。根据你的目录树,你需要上 2 个目录,本质上是回到 root/home 目录,然后再下一个目录到 public 文件夹。

在你的脚本中试试这个路径:../../public/images/wave.png

【讨论】:

  • 我只是把你的建议绑定了。之前的错误消失了,现在又出现了新的错误Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleParseError: Module parse failed: Unexpected character '�' (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
  • [这可能会有所帮助] (stackoverflow.com/questions/62556862/…)
猜你喜欢
  • 2011-06-12
  • 2023-01-10
  • 2017-12-15
  • 2015-04-09
  • 2011-04-25
  • 2015-02-28
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多