Setting Up the Environment and Project Structure: Creating a Next.js 16 Project from Scratch
Setting up a Next.js 16 development environment is like renovating a new house—the scaffolding helps you lay the foundation, and the rest of the structure, layout, and configuration can all be adjusted as needed.
1. What You'll Learn
- Create a project using the
create-next-appscaffolding - Understand core directories and files such as
app/,public/,next.config.js, etc. - Start the development server and experience Turbopack's instant hot updates
- Analyzing the Key Scripts in
package.json - Configure the recommended development extensions for VS Code
2. A True Story of a Front-End Newbie
(1) Pain Point: It takes three days to set up the development environment
Charlie is a front-end beginner who has just learned React and wants to try Next.js. He opens the official documentation and, faced with a dozen configuration options and three different scaffolding commands, has no idea which one to choose:
"With
create-react-app, I can get it running with just one command. But with Next.js, do I need thesrc/directory? Do I need TypeScript? Do I need ESLint? Do I need Tailwind? Just figuring out these choices took me two days."
He also encountered the following problems:
| Issue | Symptoms |
|---|---|
| Trouble Choosing Settings | 7 options—not sure which ones to enable |
| I don't understand the directory structure | The roles of app/, public/, and styles/ are unclear |
| Hot reload is too slow | With Webpack, I have to wait 1–2 seconds every time I save |
| No assistance in VS Code | No hints, no autocomplete—it’s like writing in Notepad |
(2) The create-next-app Solution
Use the
create-next-appinteractive scaffolding to generate a best-practice project structure with a single click.
# An interactive command,Just answer a few simple questions
npx create-next-app@latest taskflow --ts --tailwind --app --src-dir --import-alias "@/*"
(3) Revenue
| Dimension | Before (manual setup) | After (create-next-app) |
|---|---|---|
| Project Setup Time | 2 days of research | 3 minutes |
| HMR Speed | 1-2s (Webpack) | 3-10ms (Turbopack) |
| Code Hints | None | JSX autocomplete + Tailwind class name hints |
| Understanding the Table of Contents | Confusion | Organized by function, easy to understand |
3. The create-next-app Scaffold
(1) Interactive Creation
# Run the scaffolding command
npx create-next-app@latest
You'll see the following interactive options:
? What is your project named? taskflow
? Would you like to use TypeScript? Yes / No
? Would you like to use ESLint? Yes / No
? Would you like to use Tailwind CSS? Yes / No
? Would you like to use `src/` directory? Yes / No
? Would you like to use App Router? (recommended) Yes / No
? Would you like to customize the import alias (`@/*` by default)? No
(2) Recommended Configuration (Used in This Tutorial)
# Recommended Options for This Course(All projects use this set)
npx create-next-app@latest taskflow ^
--typescript ^
--eslint ^
--tailwind ^
--src-dir ^
--app ^
--import-alias "@/*"
| Option | Value | Reason |
|---|---|---|
| TypeScript | Yes | Standard for production-level projects, type-safe |
| ESLint | Yes | Code quality assurance |
| Tailwind CSS | Yes | Used throughout this tutorial |
| src/ directory | Yes | Separation of code and configuration |
| App Router | Yes | Next.js 16 default routing system |
| Import Alias | @/* | Concise import path |
▶ Example: Complete Process for Creating Scaffolding
# ============================================
# Create a file named shophub New Project
# ============================================
npx create-next-app@latest shophub --ts --tailwind --app --src-dir
# Console Output
cd shophub
npm run dev
Output:
Creating a new Next.js project in C:\Users\Charlie\shophub.
✔ 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 to use `src/` directory? … Yes
✔ Would you like to use App Router? (recommended) … Yes
✔ Would you like to customize the import alias? … @/*
Success! Created shophub at shophub
Inside that directory, you can run:
npm run dev # Start the development server
npm run build # Build the production version
npm start # Start the production server
(3) Project Structure Generated by Scaffold
graph TB
A[shophub/] --> B[src/]
A --> C[public/]
A --> D[Other Profiles]
B --> E[app/]
B --> F[app/globals.css]
B --> G[app/layout.tsx]
B --> H[app/page.tsx]
C --> I[favicon.ico]
C --> J[Images and other static resources]
D --> K[package.json]
D --> L[tsconfig.json]
D --> M[next.config.ts]
D --> N[tailwind.config.ts]
D --> O[postcss.config.mjs]
style B fill:#d4edda
style C fill:#f8d7da
style E fill:#cce5ff
4. Detailed Explanation of the Project Directory Structure
(1) src/app/ — The Core of Your Application Code
| File | Purpose | Required? |
|---|---|---|
layout.tsx |
Root layout (encloses all pages) | ✅ Required |
page.tsx |
Home (Routed via /) |
✅ Required |
globals.css |
Global Styles | Recommended |
favicon.ico |
Website Icon | Optional |
▶ Example: The default app/page.tsx file
// ============================================
// create-next-app Default Home Page
// ============================================
import Image from "next/image";
export default function Home() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
src/app/page.tsx
</code>
</li>
<li>Save and see your changes instantly.</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a className="...">Deploy now</a>
<a className="...">Read our docs</a>
</div>
</main>
</div>
);
}
Output:
Open in a browser http://localhost:3000,As you can see:
- Next.js Official Logo
- "Get started by editing src/app/page.tsx" Presentation
- "Deploy now" and "Read our docs" two links
- Dark/Light Theme Responsive
(2) public/ — Static Resources Directory
public/
├── favicon.ico # Browser Tab Icons
├── file.svg # File Type Icons
├── globe.svg # Earth icon
├── next.svg # Next.js Logo
├── vercel.svg # Vercel Logo
└── window.svg # Window Icon
All files located under public/ can be accessed directly via the / root path:
// Reference in a component public Images in the directory
<img src="/logo.png" alt="Logo" />
// or use next/image Components
import Image from 'next/image';
<Image src="/logo.png" alt="Logo" width={200} height={100} />
(3) Root Configuration File
| File | Purpose | Frequency of Modification |
|---|---|---|
next.config.ts |
Next.js compile-time configuration | Low (configured when the project starts) |
tsconfig.json |
TypeScript compilation options | Low |
tailwind.config.ts |
Tailwind CSS Themes/Plugins | Chinese (Add Custom Colors) |
postcss.config.mjs |
PostCSS plugin configuration | Very low |
package.json |
Project Dependencies + NPM Scripts | Medium (when adding dependencies) |
.eslintrc.json |
ESLint rule | Low |
▶ Example: Configuring next.config.ts
// ============================================
// next.config.ts — Next.js Compile-Time Configuration
// ============================================
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
// Allow external images to be loaded from specified domains
images: {
remotePatterns: [
{
protocol: "https",
hostname: "fakestoreapi.com",
},
{
protocol: "https",
hostname: "images.unsplash.com",
},
],
},
// Enable PPR(Partial Prerendering)
experimental: {
ppr: true,
},
};
export default nextConfig;
Output:
After the configuration takes effect:
1. <Image> components can load images from fakestoreapi.com and images.unsplash.com
2. On the page Suspense Content after the boundary will use PPR Streaming Rendering
3. Run Again npm run dev The configuration will take effect afterward
5. Development Servers and Turbopack
(1) Start the development server
# Go to the project directory
cd shophub
# Start the development server
npm run dev
▶ Example: Turbopack Live Hot Reload Experience
# ============================================
# Start the development server,Observation Turbopack At top speed HMR
# ============================================
npm run dev
# Console Output
> shophub@0.1.0 dev
> next dev
▲ ▲
▲ Next.js 16.2
▲ - Local: http://localhost:3000
▲ - Turbopack: ✓ loaded in 742ms
✔ Compiled /src/app/page.tsx in 142ms (modules: 523)
Now edit src/app/page.tsx to change any text, then save:
✔ Updated /src/app/page.tsx in 4ms ← 4 milliseconds!Updates almost instantly
Compared to Webpack:
| Operation | Webpack (v15) | Turbopack (v16) | Performance Improvement |
|---|---|---|---|
| Cold Start | 5–10 s | 0.7–1.2 s | 8x |
| Single-file hot reload | 50–200 ms | 2–10 ms | 20x |
| Large Project Builds | Baseline | 10x Faster | 10x |
(2) npm run build Production Build
# Build the production version
npm run build
Output:
✓ Linting and checking validity of types
✓ Collecting page data
✓ Generating static pages (5/5)
✓ Collecting build traces
✓ Finalizing page optimization
Route (app) Size First Load JS
┌ ○ / 5.1 kB 89 kB
├ ○ /_not-found 152 B 84.1 kB
└ λ /api/hello 0 B 84.1 kB
+ First Load JS shared by all 84.1 kB
├ chunks/main-app ...
└ chunks/webpack ...
○ (Static) Static Generation(SSG)
λ (Dynamic) Dynamic Rendering(SSR)
▶ Example: "npm run build" displays the route type
# ============================================
# Interpreting Production Build Output
# ============================================
# Suppose two pages have been created:
# app/about/page.tsx and app/dashboard/page.tsx
# Among them dashboard Used cookies() Dynamic Functions
npm run build
# Meaning of Symbols in the Output:
○ / # Static Page(No dynamic functions)
○ /about # Static Page
λ /dashboard # Dynamic Pages(Used dynamic API)
○ /_not-found # 404 Page
Output:
Route (app) Size First Load JS
┌ ○ / 5.1 kB 89 kB
├ ○ /about 3.2 kB 87 kB
├ λ /dashboard 6.8 kB 92 kB
└ ○ /_not-found 152 B 84.1 kB
(3) npm start Production Server
# Start the production server after deployment
npm run build
npm start
npm start must be run after npm run build; it launches the optimized production version, not the development version.
6. Understanding the Scripts in package.json
(1) List of Default Scripts
{
"name": "shophub",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "^16.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"typescript": "^5.7.0",
"tailwindcss": "^4.0.0",
"eslint": "^9.0.0",
"@eslint/eslintrc": "^3.0.0"
}
}
| Script | Command | Purpose |
|---|---|---|
npm run dev |
next dev |
Start the development server (Turbopack) |
npm run build |
next build |
Production Build |
npm start |
next start |
Start Production Server |
npm run lint |
next lint |
Code Style Check |
▶ Example: Adding a Custom Script
// ============================================
// Add commonly used custom scripts in package.json
// ============================================
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"type-check": "tsc --noEmit",
"format": "prettier --write .",
"preview": "npm run build && npm start"
}
}
Output:
npm run type-check → Run TypeScript Type Checking(Do not output a file)
npm run format → Format all code with Prettier
npm run preview → Build first, then start the production server(Done with a single command)
7. Recommended VS Code Extensions
(1) Core Plugins
| Plugin Name | Purpose | Number of Installs |
|---|---|---|
| Tailwind CSS IntelliSense | Tailwind class name autocomplete + hover preview | 10M+ |
| ES7+ React/Redux/React-Native snippets | JSX snippets (rafce → component template) |
8M+ |
| Prettier - Code Formatter | Automatic code formatting | 40M+ |
| Error Lens | Inline error messages | 5M+ |
| GitLens | Git History Visualization | 15M+ |
▶ Example: VS Code Configuration
// ============================================
// .vscode/settings.json — Project-level VS Code Layout
// ============================================
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"tailwindCSS.experimental.classRegex": [
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]
],
"typescript.preferences.importModuleSpecifier": "non-relative"
}
Output:
After the configuration takes effect:
1. Automatically format the file every time it is saved(Prettier)
2. Auto-Repair ESLint Question
3. Tailwind CSS Class Name Autocomplete(Input "flex" → Show All flex Variants)
4. TypeScript Import and Use @/ Alias Path
▶ Example: Quickly Create a Page Using Code Snippets
// ============================================
// Usage ES7+ React Plugin Creates a New Page
// Create a New File src/app/about/page.tsx
// Input "rafce" Enter,Automatically Generate Templates
// ============================================
// Input rafce → Automatically expand to:
import React from 'react'
const page = () => {
return (
<div>page</div>
)
}
export default page
// Manually modify to match the actual page content:
export default function AboutPage() {
return (
<div className="p-8">
<h1 className="text-3xl font-bold">About Us</h1>
<p className="mt-4 text-gray-600">
TaskFlow helps teams collaborate on projects.
</p>
</div>
);
}
Output:
Access via a browser http://localhost:3000/about
See:
About Us
TaskFlow helps teams collaborate on projects.
8. Complete Example: Building a TaskFlow Project from Scratch
# ============================================
# Comprehensive Example:Build a Complete System from Scratch Next.js 16 Project
# TaskFlow — Project Collaboration Management Platform
# ============================================
# 1. Create a Project
npx create-next-app@latest taskflow ^
--typescript ^
--eslint ^
--tailwind ^
--src-dir ^
--app ^
--import-alias "@/*"
# 2. Go to the project directory
cd taskflow
# 3. View Directory Structure
tree . /F | findstr /r "^.*src" > nul && dir /s /b src
# 4. Start the development server
npm run dev
# 5. In another terminal,Add Recommended VS Code Layout
mkdir .vscode
// .vscode/settings.json — Project-Level Configuration
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"typescript.preferences.importModuleSpecifier": "non-relative"
}
// src/app/page.tsx — Change the homepage to TaskFlow Welcome Page
import Link from "next/link";
export default function Home() {
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
<div className="container mx-auto px-4 py-16 text-center">
<h1 className="text-5xl font-bold text-gray-900 mb-4">
TaskFlow
</h1>
<p className="text-xl text-gray-600 mb-8 max-w-2xl mx-auto">
A collaborative project management platform built with Next.js 16.
Plan, track, and deliver projects together.
</p>
<div className="flex gap-4 justify-center">
<Link
href="/login"
className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
>
Get Started
</Link>
<Link
href="/about"
className="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50"
>
Learn More
</Link>
</div>
<div className="mt-16 grid grid-cols-3 gap-8 max-w-3xl mx-auto">
<div className="p-6 bg-white rounded-xl shadow-sm">
<h3 className="font-bold text-lg">Plan</h3>
<p className="text-gray-500 mt-2">Create projects and assign tasks</p>
</div>
<div className="p-6 bg-white rounded-xl shadow-sm">
<h3 className="font-bold text-lg">Track</h3>
<p className="text-gray-500 mt-2">Monitor progress in real-time</p>
</div>
<div className="p-6 bg-white rounded-xl shadow-sm">
<h3 className="font-bold text-lg">Deliver</h3>
<p className="text-gray-500 mt-2">Ship projects on schedule</p>
</div>
</div>
</div>
</div>
);
}
Expected Output:
In the browser http://localhost:3000 See:
[TaskFlow Title]
A collaborative project management platform built with Next.js 16.
Plan, track, and deliver projects together.
[Get Started] [Learn More]
┌──────┐ ┌──────┐ ┌──────┐
│ Plan │ │ Track│ │Deliver│
└──────┘ └──────┘ └──────┘
❓ FAQ
create-next-app Do I have to include parameters like --ts --tailwind?src/ What are the benefits of using a directory structure? Is it required?src/ A directory structure separates the application code (src/) from the configuration files (root directory), making the project structure clearer. It is not required, but this tutorial recommends using one. You can also choose not to use it, in which case the app/ directory is placed directly in the root directory.npm run dev (development mode). If you’re using npm start, that’s the production server; you’ll need to switch back to npm run build. Also, Turbopack defaults to hot reloading rather than a full page refresh, so changes to styles or tags should take effect immediately.experimental.turbopack: false in next.config.ts to fall back to Webpack. However, Next.js 16 officially recommends using Turbopack, and Webpack support may be removed in future versions..vscode/settings.json be committed to Git?.vscode/launch.json (debug configurations) vary from person to person, so they do not need to be committed.^ prefix before the Next.js version number in package.json mean?^16.2.0 indicates that npm install is allowed to install the latest minor version within the 16.x.x range (e.g., 16.3.0, 16.4.0), but it will not upgrade to 17.0.0. ~16.2.0 only allows 16.2.x. To lock the version, use 16.2.0 without the prefix.📖 Summary
create-next-appis the official scaffolding tool; you can create a best-practice project with a single command- Recommended setup: TypeScript + ESLint + Tailwind + App Router + src/ directory
src/app/stores route pages;public/stores static resourcesnext.config.tsis the core configuration file (image domain, PPR toggle, etc.)npm run devUsing Turbopack for hot reloading is 10 to 50 times faster than Webpacknpm run build+npm startis the process for setting up and starting the production environment- Recommended VS Code extensions: Tailwind CSS IntelliSense, ES7+ React snippets, Prettier
npm run devis for development only;npm startmust be built before use
📝 Exercises
-
Basic Exercise (⭐): Use
create-next-appto create a new project namedmy-next-app(with TypeScript, Tailwind, and App Router enabled), start the development server, openlocalhost:3000in your browser, and take a screenshot of the home page. -
Advanced Exercise (⭐⭐): Configure
remotePatternsinnext.config.tsto allow loading images fromimages.unsplash.com, then use the<Image>component inapp/page.tsxto load an Unsplash image (width 800, height 600). -
Challenge (⭐⭐⭐): Create two pages,
app/about/page.tsxandapp/contact/page.tsx; configure.vscode/settings.jsonto automatically format when saved; runnpm run buildto view the○andλsymbols in the output; and interpret the type of each route.



