前陣子使用 Next.js SSG 靜態頁面遇到問題,記錄一下:

SSG build time 時報錯

log 如下:

Error: Image Optimization using Next.js' default loader is not compatible with `next export`.
  Possible solutions:
    - Use `next start` to run a server, which includes the Image Optimization API.
    - Use any provider which supports Image Optimization (like Vercel).
    - Configure a third-party loader in `next.config.js`.
    - Use the `loader` prop for `next/image`.

自從 Next.js 推出 自己優化過後的 Image 元件後,從官方 create-next-app 建立預設專案內容,我們建好預設my-app 專案後什麼也不做直接下 next build && next export 就會跳這錯誤,因為 next Image 會仰賴 Next Server 服務,SSG 自然會出問題。

好 OK,靜態頁面 SSG 不用 Image 元件沒關係,改回原本的 HTML <img> 總可以了吧,殊不知 Next ESLint 馬上逼逼叫:

Do not use <img>. Use Image from 'next/image' instead.

......恩好喔

目前社群已有不少討論,可見此篇 Github Issues 討論。推測未來官方會解掉此問題,暫時解法有幾種,其中一種一樣使用 Next 的 Image 元件,然後在 next.config.js 多加上 images 的設定,之後重 build 和 export 就正常了。

module.exports = {
  images: {
    loader: "imgix",
    path: "/",
  },
  // 略...
};

參考

https://github.com/vercel/next.js/issues/21079
https://github.com/vercel/next.js/issues/8158#issuecomment-687707467