首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NextJS中静态图像数据的正确编码

NextJS中静态图像数据的正确编码
EN

Stack Overflow用户
提问于 2022-06-14 16:25:51
回答 1查看 374关注 0票数 2

我正在对一个新项目(下一个v12项目)尝试一种纯静态的方法,构建5-6个数据文件以输入getStaticProps。下面是数据文件的一个形状(但它们都是相似的):

代码语言:javascript
复制
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中时,情况就是这样。

代码语言:javascript
复制
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的关系。

EN

回答 1

Stack Overflow用户

发布于 2022-06-25 10:32:21

  1. 个人认为base64在这里使用是正确的。最好将bease64编码与数据URI方案bease64结合使用。

您可以使用下面的助手函数来获得带有URI方案的图像基64编码

代码语言:javascript
复制
// Helper function
function base64EncodeJpg(file) {
    return "data:image/jpg;base64," + fs.readFileSync(file, 'base64');
}

创建bestPlacesList时,

  1. 使用助手函数

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72620393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档