【发布时间】:2020-06-04 08:10:00
【问题描述】:
我查看了这个文档,Static File Serving,它明确指出:
Next.js 可以在根目录中名为 public 的文件夹下提供静态文件,例如图像。然后,您的代码可以从基本 URL (/) 开始引用 public 中的文件。
我已经在public文件夹中放了一个名为background.jpg的图片文件。
然后在我的pages/referral.js 我有以下代码:
import React from 'react';
import backgroundImage from '/background.jpg'; // later I removed this
const styles = {
container: {
backgroundImage: `url(${backgroundImage})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
width: '100vw',
height: '100vh'
}
};
export default class Referral extends React.Component{
render(){
return(
<div className="cComponent" style={styles} >
<h1 align="center">Some item</h1>
</div>
)
}
}
然后我收到此错误:Module not found: Can't resolve '/background.jpg' in referral.js。
我尝试了什么:
const backgroundImage = require('/background.jpg'); <-- and tried thisimport backgroundImage from '/public/background.jpg';import backgroundImage from './background.jpg'
上述所有尝试也会得到相同的错误。
我什至尝试添加next.config.js:
// next.config.js
const withImage = require('next-images');
module.exports=withImage({});
然后像这样导入pages/referral.js:
import backgroundImage from '/background.jpg';
也会出现同样的错误:Module not found: Can't resolve '/background.jpg' in referral.js。
我在这里错过了什么?也有人可以给我一个关于如何将背景图像放入组件的示例吗?
【问题讨论】:
-
const backgroundImage = require('public/background.jpg')
-
@bcjohn 先生同样的错误。
Module not found: Can't resolve '/public/background.jpg'
标签: javascript next.js