Skip to content

Next.js - 环境搭建

搭建 Next.js 开发环境非常简单。由于 Next.js 基于 React 和 Node.js 构建,你需要在系统上安装 Node.js。

  1. 安装 Node.js: 从官方网站 (https://nodejs.org/) 下载并安装最新长期支持版(LTS)的 Node.js。这也会同时安装 npm (Node Package Manager) 或 yarn(如果你偏好使用后者)。

  2. 验证安装: 打开你的终端或命令提示符,运行:

node -v
npm -v

这些命令应该会输出安装的 Node.js 和 npm 版本号。

创建新的 Next.js 应用的推荐方法是使用官方的 create-next-app CLI 工具。打开你的终端,切换到你希望创建项目的目录,然后运行:

npx create-next-app@latest my-nextjs-app

(将 my-nextjs-app 替换为你希望的项目名称)。

安装程序会询问你几个问题来配置你的项目,例如是否使用 TypeScript、ESLint、Tailwind CSS、src/ 目录,以及 App Router(推荐)或 Pages Router。选择最符合你需求的选项。对于初学者,接受默认选项是一个很好的开始。

安装过程中的示例提示(可能会随更新略有不同):

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router (recommended)? … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes
Creating a new Next.js app in /path/to/your/projects/my-nextjs-app.
...

安装完成后,进入你的新项目目录:

cd my-nextjs-app

在项目内部,你会看到一个标准的结构,包括:

  • app/ 或 pages/: 包含你的应用程序的路由和组件(取决于你选择了 App Router 还是 Pages Router)。
  • public/: 用于静态资源,如图片和字体。
  • package.json: 列出项目依赖和脚本。
  • next.config.js: Next.js 的配置文件(可选,如果需要则创建)。

package.json 文件将已经包含必要的依赖(next、react、react-dom)和脚本。

你的 package.json 文件将包含如下脚本:

"scripts": {
"dev": "next dev", // Starts the development server
"build": "next build", // Builds the application for production
"start": "next start", // Starts the production server (after building)
"lint": "next lint" // Runs ESLint (if configured)
}

要在你的项目目录中启动开发服务器,运行以下命令:

npm run dev

(如果你偏好 Yarn,则运行 yarn dev)。

你应该会看到表明服务器已启动的输出,通常在端口 3000 上:

# Example Output:
# - ready started server on 0.0.0.0:3000, url: http://localhost:3000
# - event compiled client and server successfully in 245 ms (18 modules)

打开你的 Web 浏览器并导航到 http://localhost:3000。你应该会看到默认的 Next.js 启动页面,这确认你的环境已正确搭建,并且应用程序正在运行。