Next.js - 環境設定



由於 Next.js 是基於 React 的框架,我們使用的是 Node 環境。現在確保已在系統中安裝了 Node.jsnpm。可以使用以下命令安裝 Next.js −

npm install next react react-dom

在成功安裝 Next.js 後,可以看到以下輸出 −

+ react@16.13.1
+ react-dom@16.13.1
+ next@9.4.4
added 831 packages from 323 contributors and audited 834 packages in 172.989s

現在,讓我們建立一個節點 package.json −

npm init

在建立 package.json 時選擇預設值 −

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nextjs)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to \Node\nextjs\package.json:
{
   "name": "nextjs",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "dependencies": {
      "next": "^9.4.4",
      "react": "^16.13.1",
      "react-dom": "^16.13.1"
   },
   "devDependencies": {},
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
   },
   "author": "",
   "license": "ISC"
}
Is this OK? (yes)

現在更新 package.json 的指令碼部分,以包含 Next.js 命令。

{
   "name": "nextjs",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "dependencies": {
      "next": "^9.4.4",
      "react": "^16.13.1",
      "react-dom": "^16.13.1"
   },
   "devDependencies": {},
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "dev": "next",
      "build": "next build",
      "start": "next start"
   },
   "author": "",
   "license": "ISC"
}

建立 pages 目錄。

在 nextjs 資料夾內建立一個 pages 資料夾,並建立一個名為 index.js 的檔案,其內容如下。

function HomePage() {
   return <div>Welcome to Next.js!</div>
}

export default HomePage

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

First Application
廣告