简体   繁体   中英

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

Using absolute path in img src solves my problem, but the reason causing original problem is unknown.

I add a custom prefix to NEXT routing, and I didn't use NEXT/IMG to render profile photo. I guess it's the reason why img src attribute doesn't change according to Next path prefix config.


Original Question

I am creating my first online portfolio using Next + React, and then published to github pages. There is one photo in the portfolio homepage.

  • When I first visit the page, the photo rendered correctly
  • but if navigate to other same-site pages, and then would like to visit homepage again by clicking site logo, which is a Next/Link point back to home page. The photo is not rendered
  • there is a floating button on bottom-right corner using the same photo, it always rendered correctly
  • Github Repo : main branch is the active branch
  • warning: my code is definitely structured horribly. It might hurt your eyes ...

my profile picture is named Avatar.png stored in public folder

this is where the code is returning my profile photo

// 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

I notice that there is additional '/' appended to the end of url when first visit


Currently, I have a workaround is to make about.js to become a standalone page. (although I don't feel like to do so ...)

for people who encounter similar problem: use absolute path instead of relative path will solve this problem. However, I haven't figured the reason why this problem comes up at first place.

more details:

  • I add basePath in next.config.js

    next.config.js

     const nextConfig={ ... basePath: '/personal-portfolio' }
  • When this Next project deployed to gitHub, this is the img src rendered

     // 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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