Next.js - 全域性 CSS 支援



在 Next.js 中,我們來建立將在所有頁面上應用的全域性樣式。

在此示例中,我們將建立一個 styles.css,該檔案將在所有構件中使用 _app.js 構件。

更新在 CSS 支援 章節中使用的 nextjs 專案。

首先在根級別建立一個 styles 目錄,然後新增一個如下所示的 styles.css 檔案 −

html,
body {
   padding: 0;
   margin: 0;
   line-height: 1.6;
   font-size: 18px;
   background-color: lime;
}

* {
   box-sizing: border-box;
}

a {
   color: #0070f3;
   text-decoration: none;
}

a:hover {
   text-decoration: underline;
}

img {
   max-width: 100%;
   display: block;
}

在頁面目錄中建立一個 _app.js 檔案

import '../styles/styles.css'

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

啟動 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,您將看到以下輸出。

Styled Home page

單擊第一篇文章連結。

Styled First page
廣告