Next.js - 靜態檔案提供



在 Next.js 中,我們可以非常輕鬆地透過將靜態頁面(如影像)放入頂級目錄 **public** 中來提供服務。我們可以在 **pages** 目錄中的頁面中以類似的方式引用這些檔案。

在 Next.js 中,頁面是一個 React 元件,並從 pages 目錄匯出。每個頁面都根據其檔名與一個路由相關聯。

讓我們更新在 頁面 章節中使用的 nextjs 專案。

建立 public 目錄並在其中放置任何影像。我們採用了 logo.png,TutorialsPoint Logo 影像。

按照以下方式更新 first.js −

import Link from 'next/link'

export default function FirstPost() {
   return (
      <>
         <h1>My First Post</h1>
         <h2>
            <Link href="/">
               <a>Home</a>
            </Link>
         </h2>
         <br/">
         <img src="/logo.png" alt="TutorialsPoint Logo" />
      </>	  
   )
}

這裡我們在 index.js 檔案中添加了對 logo.png 的引用。

啟動 Next.js 伺服器

執行以下命令來啟動伺服器 −.

npm run dev
> nextjs@1.0.0 dev \Node\nextjs
> next

ready - started server on https://:3000
event - compiled successfully
event - build page: /
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

驗證輸出

在瀏覽器中開啟 localhost:3000,你將看到以下輸出。

Home page with Logo

public 目錄在 SEO 目標方面也很有用。可用於 Google 網站驗證或 Web 應用程式中的任何其他靜態資產中的 robot.txt。

廣告