简体   繁体   English

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

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

The images not loading from CSS file which is used for the background but in jsx it's loading图像不是从用于背景的 CSS 文件加载的,而是在 jsx 中加载的

In the CSS file, I have used like below在 CSS 文件中,我使用如下

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

the image URL is absolutely fine图片网址绝对没问题

And configuration file like this和这样的配置文件

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

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

what is the issue actually?实际上是什么问题?

Thanks谢谢

Your static files are being deployed to the web's root.您的静态文件正在部署到 Web 的根目录。 Same as your compiled js and css files.与您编译的 js 和 css 文件相同。

So you can access them with the following url: url(/static/images/banner-bg1.jpg)因此,您可以使用以下网址访问它们: url(/static/images/banner-bg1.jpg)

More information about that on this github issue.有关github 问题的更多信息。

I recieved [object Module] in css prop background-image.我在 css prop background-image 中收到了 [object Module]。 flag esModule: false in url-loader options fixed that problem. 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