[Next.js] Next.js 新手教學筆記 — _app.js用處

施慶銓

檔名介紹

Next.js專案結構中, 可以在 /pages 資料夾底下, 新增一個 _app.js , 這個檔案跟其他檔案不同的地方是, 其檔名一定要 _ 開頭, 在一般的程式語言中, _ 開頭的檔名, 通常代表這的檔案是 私有 的檔案. 在這裏我認為可以解讀成

告訴Next.js在利用pages 底下的檔案建立網站路由時, 忽略這個檔案. 所以這個網站不會有一個網址是 https://xxx/_app

基本用法

初始化網頁

_app.js 主要的用處在於: 針對每一個 /pages 底下的頁面在初始化 時加入客製化的樣式

例如目前的網站結構是

/pages
- index.js
- _app.js
- /posts
- index.js
- profile.js

網站建立之後, 可拜訪的網址是

- https://xxx/
- https://xxx/profile
- https://xxx/posts

在拜訪每一頁時, 會先讀取 _app.js 的內容, 建立該頁面的基本結構, 如果 _app.js 的結構是

// _app.js

function MyApp({ Component, pageProps }) {
return (
<div>
<header>共享導航欄</header>
<Component {...pageProps} />
<footer>共享頁腳</footer>
</div>
);
}

export default MyApp;

這樣網站每一頁都會有 共享導航欄共享頁腳

註1:
Component: 代表當前頁面
pageProps: 傳入給當前頁面的prop

註2:
pageProps 的資料來源通常是透過, Next.js提供開發者取得API 資料的方法所回傳的資料(Data Fetching文件)

官網介紹: https://nextjs.org/docs/pages/building-your-application/routing/custom-app

設定Global CSS

官網文件特別提到

Good to know: This is different from the pages directory, where you can only import global styles inside the _app.js file.

官網文件: https://nextjs.org/docs/app/building-your-application/styling/css-modules#global-styles

所以, 要將global CSS 套用到各個頁面上只能在 _app.js 檔案內引入. 範例如下

import '../styles/globals.css';

function App({ Component, pageProps }) {
return (<Component {...pageProps} />)
}

export default App

這樣global CSS就套用到每個頁面上

References

No responses yet

Write a response