You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Parcel v2部署至GitHub Pages时动态图片无法显示求助

解决GitHub Pages上动态加载图片404的问题

问题根源

控制台报错的请求路径是https://bigyajuu.github.io/img/works/xxx,但实际部署后图片存储在https://bigyajuu.github.io/my-portfolio/img/works/xxx——因为你的项目部署在GitHub Pages的子路径my-portfolio下,而动态拼接的图片路径未适配这个子路径,导致请求指向了根域名的错误位置。

解决方案

1. 修正动态图片的路径格式

打开/src/ts/engine/mixin-components/overview-dialog.ts,检查this.images[i].path的取值:

  • 如果路径是以/开头的绝对路径(比如/img/works/project1.jpg),删除开头的/,改为相对路径格式img/works/project1.jpg。
  • 这样页面加载时会基于当前URL的目录(https://bigyajuu.github.io/my-portfolio/)自动拼接成正确的路径:https://bigyajuu.github.io/my-portfolio/img/works/project1.jpg。

2. 配置parcel-reporter-static-files-copy插件

在package.json中添加插件的明确配置,确保根目录的img/文件夹被完整复制到dist/img/:

{
  // ...其他已有配置
  "staticFiles": {
    "staticPath": "img",
    "distPath": "img",
    "watcherGlob": "**"
  }
}

3. 调整predeploy脚本的public-url参数

由于项目部署在my-portfolio子路径下,需要指定--public-url为子路径,让Parcel自动处理所有静态资源的路径前缀:

"scripts": {
  // ...其他脚本
  "predeploy": "parcel build src/index.html --public-url /my-portfolio/ && cp src/.htaccess dist"
}

4. 本地验证

执行npm run predeploy构建产物,打开dist/index.html检查动态加载的图片路径是否正确,确认图片能正常显示后再部署到GitHub Pages。

你之前用parcel build src/index.html img/**能本地显示,是因为Parcel把img/**作为构建入口的一部分自动处理了路径,但这种方式不规范,用parcel-reporter-static-files-copy插件是更合适的静态资源管理方式。

内容的提问来源于stack exchange,提问作者BigYajuu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:15:17