You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在GitHub Pages部署Next.js应用时图片无法加载的问题求助

Fixing Image Loading Issues with Next.js on GitHub Pages

I’ve run into this exact problem before when deploying Next.js apps to GitHub Pages—let’s get your images loading correctly without manual URL edits.

The Root of Your Issue

Your current next.config.ts has conflicting settings: you’re using the imgix loader alongside unoptimized: true, which disables Next.js’s built-in image optimization. When you set output: 'export' for static deployment, the imgix loader isn’t necessary here, and it’s overriding the automatic path handling from basePath.

Corrected Configuration

Update your next.config.ts to this simplified version—this will make Next.js automatically prepend your repository name to all asset paths, including images:

import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  output: 'export',
  basePath: '/repository_name', // Match your GitHub repo name exactly
  images: {
    unoptimized: true, // Critical for static export—disables optimization, uses native img tags
  },
};

export default nextConfig;

Why This Works

  • basePath: '/repository_name': Tells Next.js to add this prefix to all asset URLs (images, CSS, JS) during the static export. So <Image src="/portrait.jpg" /> will become <img src="/repository_name/portrait.jpg" /> in the final HTML.
  • unoptimized: true: When exporting statically, Next.js can’t run its image optimization server, so this setting switches to plain <img> tags instead of the optimized Next.js Image component’s runtime logic. This ensures the basePath is correctly applied to the image source.

Additional Checks

  • Image Location: Make sure your image (portrait.jpg) is in the public folder of your Next.js project. Files in public are served at the root of your deployed site, so /portrait.jpg maps to public/portrait.jpg.
  • Rebuild and Redeploy: After updating the config, run npm run build (or yarn build) again, then push the updated out folder to your GitHub Pages branch. Old build artifacts might be cached, so ensure you’re deploying the latest generated files.
  • Verify the Output: After deployment, right-click on the broken image in your browser and check the src attribute—it should now include /repository_name/ at the start.

That should resolve your image loading issue without needing to manually edit HTML files!

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

火山引擎 最新活动