Next.js教學

Next.js 教學

https://nextjs.org/

1.建立專案

1.開一個新資料夾,然後cd進去後輸入以下指令。

npm init -y
npm install --save react react-dom next

2.在package.json的script內加入以下

{
  "scripts": {
    "dev": "next"
  }
}

3.

npm run dev

4.之後應該會顯示一個404畫面,這時我們新增一下pages 資料夾,裡面放入一個index.js,內容放入以下。

const Index = () => (
  <div>
    <p>Hello Next.js</p>
  </div>
)

export default Index

5.新增其他route時只要在pages內加入檔案即可。

/pages/about.js

2.新增client Route

我們把index.js改為如下

route的文件:https://github.com/zeit/next.js#routing

3.新增共用layout component

https://nextjs.org/learn/basics/using-shared-components/the-layout-component

4.引入<script>或是其他html tag

5.讀取url

加入withRouter

之後即可讀取到router的props

6.Router Masking

也就是更改實際的client URL

as 為顯示出來的,href為實際的router

但重新整理後會無法讀取該顯示出來的router

7.自訂Server

原先為使用Next.js內建的dev server,現在要來自己建一個Server

如果有不在page內路徑url,也必須要自訂server,否則重新整理會產生404頁面。

https://github.com/zeit/next.js#custom-server-and-routing

8.使用Fetch獲取Data

把index.js改為如下

當client 跳轉到此頁面時會從client發出請求,但如果是重新整理頁面的話則是Server Side會發出請求並直接把資料渲染到頁面上。

更新版:

Next.js 9.3

https://nextjs.org/docs/api-reference/data-fetching/get-initial-props

9. Style JSX

可以如下寫css

如果要加上外部css檔案

next.config.js

然後記得import './....css' 的檔案必須寫在pages/index.js中。

10. 部署

新增以下這兩行在 package.json 的 script 中。

但如果想用自訂的Server可以在build完後使用

加上NODE_ENV=production即可,自訂的Server為上面第七點的Server

使用Nginx

他跟create-react-app 不同之處在於他是server side render,所以沒有直接build然後用serve static的方式,而是需要啟動next的server然後用nginx做reverse proxy的方式。

使用pm2

到next專案下輸入如下:

11. 部署到 Now

Now 為一個 https://zeit.co/ 所出的雲端快速建置服務,使用Heroku

安裝:

之後再項目的根目錄輸入now

記得先到網站註冊帳號

部署後會看到如下(會給你分配一個 now.sh 的子網域):

之後回到Zeit.co網站也可查看部署過的項目。

Next UI

https://nextui.org/docs/frameworks/nextjs

額外功能

1. 輸出靜態頁面

更新:可參考以下連結快速配置

https://nextjs.org/docs/app/building-your-application/deploying/static-exports

新增 next.config.js

上面的config檔案描述 route 該導向哪個檔案,以及要Render的資料。

之後輸入以下即可

會產生一個out資料夾,裡面包含一個html檔案。

可以使用Serve模組測試

如果想要部署到 Now上,進入 out 資料夾後輸入 now 即可。

Next.js 使用 antd (ant design)

新增 pages/_app.js

引入 antd style

PM2 執行 Next.js

Last updated

Was this helpful?