如何在 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;
}
图片URL绝对没问题
和这样的配置文件
//next.config.js
const withImages = require('next-images');
const withCSS = require('@zeit/next-css')
module.exports = withImages(withCSS({
cssLoaderOptions: {
url: false
}
}))
到底是什么问题?
谢谢
您的静态文件正在部署到网站的根目录。与您编译的 js 和 css 文件相同。
因此您可以使用以下 url 访问它们:url(/static/images/banner-bg1.jpg)
有关 this github 问题的更多信息。
我在 css prop background-image 中收到了 [object Module]。 url-loader 选项中的标志 esModule: false
修复了该问题。
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;
}
});
图像未从用于背景的 CSS 文件加载,但在 jsx 中它正在加载
在CSS文件中,我使用如下
.main-banner {
position: relative;
height: 910px;
z-index: 1;
background: transparent url(../../static/images/banner-bg1.jpg) right top no-repeat;
}
图片URL绝对没问题
和这样的配置文件
//next.config.js
const withImages = require('next-images');
const withCSS = require('@zeit/next-css')
module.exports = withImages(withCSS({
cssLoaderOptions: {
url: false
}
}))
到底是什么问题?
谢谢
您的静态文件正在部署到网站的根目录。与您编译的 js 和 css 文件相同。
因此您可以使用以下 url 访问它们:url(/static/images/banner-bg1.jpg)
有关 this github 问题的更多信息。
我在 css prop background-image 中收到了 [object Module]。 url-loader 选项中的标志 esModule: false
修复了该问题。
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;
}
});