繁体   English   中英

为什么发布到 GitHub Pages 时,NextJS 中不呈现 public/image?

[英]Why public/image is not rendered in NextJS when published to GitHub Pages?

img src中使用absolute path解决了我的问题,但导致原始问题的原因尚不清楚。

我为 NEXT 路由添加了一个自定义前缀,并且我没有使用NEXT/IMG来渲染个人资料照片。 我想这就是img src属性不会根据 Next 路径前缀配置而改变的原因。


原始问题

我正在使用 Next + React 创建我的第一个在线作品集,然后发布到 github 页面。 投资组合主页中有一张照片。

  • 当我第一次访问该页面时,照片正确呈现
  • 但是如果导航到其他同站点页面,然后想通过单击站点徽标再次访问主页,这是一个返回主页的Next/Link点。 照片未渲染
  • 右下角有一个浮动按钮使用同一张照片,它总是正确渲染
  • Github Repo :主分支是活动分支
  • 警告:我的代码结构非常糟糕。 可能会伤到眼睛...

我的个人资料图片名为 Avatar.png 存储在公共文件夹中

这是代码返回我的个人资料照片的地方

// components/about.js
<div className={styles['avatar-container']}>
    <img className={styles['avatar-img']} src='Avatar.png' width="188px" height="196px" alt="a picture of Yu-Ming"></img>
</div>

// about.js is a react component imported to pages/index.js

我注意到第一次访问时在 url 末尾附加了额外的“/”

  • 首次访问: https ://yumingchang1991.github.io/personal-portfolio/
  • 同站导航然后链接回: https ://yumingchang1991.github.io/personal-portfolio

目前,我有一个解决方法是让 about.js 成为一个独立的页面。 (虽然我不想这样做......)

对于遇到类似问题的人:使用绝对路径而不是相对路径将解决此问题。 但是,我还没有弄清楚这个问题首先出现的原因。

更多细节:

  • 我在next.config.js中添加 basePath

    next.config.js

     const nextConfig={ ... basePath: '/personal-portfolio' }
  • 当这个 Next 项目部署到 gitHub 时,这是渲染的img src

     // Relative Path // 1st visit img src = 'https://yumingchang1991.github.io/personal-portfolio/ProfileLarge.png' // subsequent visits when navigating to other pages and comeback to root img src = 'https://yumingchang1991.github.io/ProfileLarge.png' // subsequent visit does not add basePath correctly // so changing from Relative URL to Absolute URL fix the problem

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM