我正在对一个新项目(下一个v12项目)尝试一种纯静态的方法,构建5-6个数据文件以输入getStaticProps。下面是数据文件的一个形状(但它们都是相似的):
import SqAshland1 from '../../public/best-places-imagery/square-ashland.jpg'
const bestPlacesList = [
{
"cityName": "Ashland",
"state": "WI",
"country": "US",
"imageSquare": SqAshland1,
"slug": "ashland-wi"
},
...
]
const encodeBestPlacesList = JSON.stringify(bestPlacesList)
export default bestPlacesList当我将这个文件插入到我的/pages/best-places/[slug].js中时,情况就是这样。
export async function getStaticProps({ params, preview = false, previewData }) {
const parsedBestPlacesList = JSON.parse(bestPlacesList)
const cityData = parsedBestPlacesList.find( city => city.slug === params.slug )
return {
props: {
preview,
cityData: cityData,
},
revalidate: 60,
};
}
export async function getStaticPaths() {
const cities = JSON.parse(bestPlacesList);
return {
paths: cities?.map( (city) => ({
params: { slug: city.slug }
})),
fallback: false,
};
}它运行得很好,但是当我部署的时候,图像一直在破坏。这让我觉得我需要对图像进行base64编码,但是在哪里可以这样做,这样就不会破坏Next的图像抓取?好奇的是,是否有人尝试过这种方法,并且知道如何平衡Next和Node的关系。
发布于 2022-06-25 10:32:21
您可以使用下面的助手函数来获得带有URI方案的图像基64编码
// Helper function
function base64EncodeJpg(file) {
return "data:image/jpg;base64," + fs.readFileSync(file, 'base64');
}创建bestPlacesList时,
const bestPlacesList = [
{
"cityName": "Ashland",
"state": "WI",
"country": "US",
"imageSquare": base64EncodeJpg('../../public/best-places-imagery/square-ashland.jpg'),
"slug": "ashland-wi"
},
...
]为了确保这些路径在生产和开发中都能工作,您可以使用一个文件为图像资产定义一个基本路径,并使用这个路径而不是相对路径。https://nextjs.org/docs/basic-features/environment-variables
https://stackoverflow.com/questions/72620393
复制相似问题