【问题标题】:React app fails compile when using image url in CSS在 CSS 中使用图像 url 时,React 应用程序编译失败
【发布时间】:2017-12-10 22:33:53
【问题描述】:

我正在尝试使用 css 及其 url 功能将背景图像添加到 ReactJS 项目中的控件。

.jumbotron {
    background-image: url(../images/image.jpeg); 
    background-position: center;
    background-repeat: no-repeat;
    background-size: 100% auto;
    color: 6b6b6b;
}

但是,加载程序正在中断,因为它正在尝试解析二进制文件。一个意想不到的字符。删除背景线,一切正常。

我正在使用 webpack,我的模块是这样加载的:

module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            },
            {
                rules: [
                  {
                    test: /\.css$/,
                    use: [ 'style-loader', 'css-loader' ]
                  }
                ]
              }
        ]
    }

如何让我的 React 应用将此 CSS 图像用作背景网址?使用 create-react-app 创建项目 - 它可以工作,但我看不到它是如何处理图像的。

我有一个回购: https://github.com/CraigInBrisbane/ReactLearning

任何帮助都会很棒。

【问题讨论】:

  • 不应该是url("../images/image.jpeg")吗?注意引号。
  • 我可以尝试一下,但是当我使用 create-react-app 创建项目时,它就是这样工作的(不带引号)。现在,手动创建一个项目结构,创建我自己的 webpack.config 等......并拉入我认为我需要的模块 - 失败。相同的 CSS。
  • 你试过用url-loader吗?
  • 哦!不,我会查一下。

标签: css reactjs webpack


【解决方案1】:

当你使用css-loader 时,webpack 会移除你所有的background-image: url(../images/image.jpeg); 并插入require(../images/image.jpeg)。有两种方法可以解决这个问题:

1) 为这些类型的文件添加file-loader/url-loader

2) 使用绝对路径而不是相对路径 (background-image: url(/images/image.jpeg);),css-loader 将跳过此图像

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-16
    • 2021-06-28
    • 1970-01-01
    • 2013-07-05
    • 2021-03-27
    • 1970-01-01
    • 2016-12-31
    • 2018-03-12
    相关资源
    最近更新 更多