繁体   English   中英

如何在 React 和 NextJS 中从 css 加载背景图像

[英]How to load background images from css in React and NextJS

图像不是从用于背景的 CSS 文件加载的,而是在 jsx 中加载的

在 CSS 文件中,我使用如下

.main-banner {
  position: relative;
  height: 910px;
  z-index: 1;
  background: transparent url(../../static/images/banner-bg1.jpg) right top no-repeat;
}

图片网址绝对没问题

和这样的配置文件

//next.config.js
const withImages = require('next-images');
const withCSS = require('@zeit/next-css')

module.exports = withImages(withCSS({
    cssLoaderOptions: {
        url: false
    }
}))

实际上是什么问题?

谢谢

您的静态文件正在部署到 Web 的根目录。 与您编译的 js 和 css 文件相同。

因此,您可以使用以下网址访问它们: url(/static/images/banner-bg1.jpg)

有关github 问题的更多信息。

我在 css prop background-image 中收到了 [object Module]。 flag esModule: false在 url-loader 选项中修复了这个问题。

const withCSS = require('@zeit/next-css');
const nextConfig = withCSS({
    webpack(config, options) {
        config.module.rules.push({
            test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
            use: {
                loader: 'url-loader',
                options: {
                    limit: 100000,
                    esModule: false,
                    name: '[name].[ext]'
                }
            }
        });
        return config;
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM