Next.js环境搭建 #

一、前置要求 #

1.1 Node.js安装 #

Next.js 需要 Node.js 18.17 或更高版本。

检查Node.js版本

bash
node -v

安装Node.js

macOS (使用Homebrew):

bash
brew install node

Windows (使用Chocolatey):

bash
choco install nodejs

Linux (Ubuntu/Debian):

bash
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

使用nvm管理Node.js版本

bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

nvm install 20
nvm use 20
nvm alias default 20

1.2 包管理器选择 #

包管理器 特点 推荐场景
npm Node.js自带,稳定 初学者
yarn 快速,离线缓存 团队项目
pnpm 节省磁盘空间 大型项目
bun 极速,新工具 尝鲜体验

安装pnpm

bash
npm install -g pnpm

安装yarn

bash
npm install -g yarn

安装bun

bash
curl -fsSL https://bun.sh/install | bash

1.3 代码编辑器 #

推荐使用 VS Code,并安装以下扩展:

扩展名 功能
ES7+ React/Redux/React-Native snippets React代码片段
Tailwind CSS IntelliSense Tailwind智能提示
Prettier - Code formatter 代码格式化
ESLint 代码检查
TypeScript Next.js syntax Next.js语法高亮

二、创建Next.js项目 #

2.1 使用create-next-app #

交互式创建

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

创建过程中的选项:

text
What is your project named? my-nextjs-app
Would you like to use TypeScript? Yes
Would you like to use ESLint? Yes
Would you like to use Tailwind CSS? Yes
Would you like your code inside a `src/` directory? Yes
Would you like to use App Router? Yes
Would you like to use Turbopack for `next dev`? Yes
Would you like to customize the import alias? No

非交互式创建

bash
npx create-next-app@latest my-nextjs-app \
    --typescript \
    --tailwind \
    --eslint \
    --app \
    --src-dir \
    --turbopack \
    --import-alias "@/*"

2.2 使用不同包管理器 #

npm

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

yarn

bash
yarn create next-app my-app

pnpm

bash
pnpm create next-app my-app

bun

bash
bunx create-next-app my-app

2.3 项目选项说明 #

选项 说明 推荐
TypeScript 类型安全 Yes
ESLint 代码规范检查 Yes
Tailwind CSS 原子化CSS框架 Yes
src/目录 源码目录结构 Yes
App Router 新路由系统 Yes
Turbopack 新构建工具 Yes
import alias 导入路径别名 @/*

三、项目结构 #

3.1 默认目录结构 #

text
my-nextjs-app/
├── src/
│   └── app/
│       ├── favicon.ico
│       ├── globals.css
│       ├── layout.tsx
│       ├── page.tsx
│       └── page.module.css
├── public/
│   ├── file.svg
│   ├── globe.svg
│   ├── next.svg
│   ├── vercel.svg
│   └── window.svg
├── .eslintrc.json
├── .gitignore
├── next.config.ts
├── package.json
├── postcss.config.mjs
├── README.md
├── tailwind.config.ts
└── tsconfig.json

3.2 核心文件说明 #

package.json

json
{
  "name": "my-nextjs-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "15.2.0",
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^19",
    "@types/react-dom": "^19",
    "eslint": "^9",
    "eslint-config-next": "15.2.0",
    "postcss": "^8",
    "tailwindcss": "^4",
    "typescript": "^5"
  }
}

next.config.ts

typescript
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
    /* config options here */
}

export default nextConfig

tsconfig.json

json
{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

3.3 app目录结构 #

text
src/app/
├── favicon.ico          # 网站图标
├── globals.css          # 全局样式
├── layout.tsx           # 根布局
├── page.tsx             # 首页
└── page.module.css      # 首页样式模块

四、开发命令 #

4.1 常用命令 #

命令 说明
npm run dev 启动开发服务器
npm run build 构建生产版本
npm run start 启动生产服务器
npm run lint 运行ESLint检查

4.2 开发服务器 #

bash
npm run dev

输出:

text
   ▲ Next.js 15.2.0
   - Local:        http://localhost:3000
   - Environments: .env.local

 ✓ Starting...
 ✓ Ready in 1.8s

访问 http://localhost:3000 即可看到应用。

4.3 命令选项 #

指定端口

bash
npm run dev -- -p 4000

指定主机

bash
npm run dev -- -H 0.0.0.0

使用HTTPS

bash
npm run dev -- --experimental-https

五、开发工具配置 #

5.1 ESLint配置 #

.eslintrc.json

json
{
  "extends": ["next/core-web-vitals", "next/typescript"]
}

自定义规则

json
{
  "extends": ["next/core-web-vitals", "next/typescript"],
  "rules": {
    "react/no-unescaped-entities": "off",
    "@next/next/no-page-custom-font": "off"
  }
}

5.2 Prettier配置 #

安装

bash
npm install -D prettier eslint-config-prettier

.prettierrc

json
{
  "semi": false,
  "singleQuote": true,
  "tabWidth": 4,
  "trailingComma": "es5",
  "printWidth": 100
}

package.json scripts

json
{
  "scripts": {
    "format": "prettier --write ."
  }
}

5.3 VS Code配置 #

.vscode/settings.json

json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "typescript.tsdk": "node_modules/typescript/lib"
}

.vscode/extensions.json

json
{
  "recommendations": [
    "esbenp.prettier-vscode",
    "dbaeumer.vscode-eslint",
    "bradlc.vscode-tailwindcss"
  ]
}

5.4 Git配置 #

.gitignore

gitignore
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local
.env

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

六、环境变量 #

6.1 创建环境文件 #

.env.local

bash
NEXT_PUBLIC_API_URL=https://api.example.com
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb

6.2 环境变量命名规则 #

前缀 访问位置 说明
NEXT_PUBLIC_ 客户端+服务端 公开变量
无前缀 仅服务端 私密变量

6.3 使用环境变量 #

客户端使用

tsx
console.log(process.env.NEXT_PUBLIC_API_URL)

服务端使用

tsx
console.log(process.env.DATABASE_URL)

类型定义 env.d.ts

typescript
namespace NodeJS {
    interface ProcessEnv {
        NEXT_PUBLIC_API_URL: string
        DATABASE_URL: string
    }
}

七、常见问题 #

7.1 端口被占用 #

bash
# macOS/Linux
lsof -i :3000
kill -9 <PID>

# 或使用其他端口
npm run dev -- -p 3001

7.2 依赖安装失败 #

bash
# 清除缓存
rm -rf node_modules
rm -rf .next
rm package-lock.json

# 重新安装
npm install

7.3 TypeScript错误 #

bash
# 重新生成类型
rm -rf .next
npm run dev

八、总结 #

环境搭建要点:

步骤 说明
安装Node.js 版本 >= 18.17
创建项目 create-next-app
安装依赖 npm install
启动开发 npm run dev

推荐配置:

  • TypeScript:类型安全
  • ESLint:代码规范
  • Tailwind CSS:样式开发
  • App Router:新路由系统

下一步,让我们创建第一个 Next.js 应用!

最后更新:2026-03-28