之前用agent做了一个站
原本是打算做一个插件发布网站
agent用的是技术栈:Next.js 16(App Router + cacheComponents)· TypeScript · Tailwind CSS v4 · shadcn/ui · Font Awesome · Supabase(Auth + PostgreSQL)· Vercel 部署
起初是各种功能都正常不过后来我就掌控不了了,因为实在是看不懂项目的结构还有后端和数据库的逻辑,然后就不得不废弃掉,不过证明了ai确实可以做到全栈了,不过没有人指点下确实一言难尽
所以我重新构建,必须要100%了解用到的技术避免整个结构变成不可维护的黑盒,不然也是浪费token
Nextjs介绍
Next.js 是一个用于构建全栈 Web 应用的 React 框架。你可以使用 React 组件来构建用户界面,而 Next.js 则用于实现额外的功能和优化
需要掌握的知识
HTML + CSS + React +Javascript +Typescript
详细内容参考Nextjs官网
安装Nextjs
在此之前我们需要知道nextjs存在两种路由系统------新版的App Router(/app 目录)和 旧版的Pages Router(/pages 目录)
目前旧版仍然被长期支持但不再更新,不过我们采用新版的app router
自动安装(推荐)
首先新建仓库并克隆到本地,然后确保电脑上有nodejs 22+和pnpm(这里我用pnpm安装,因为它比 npm 或 yarn 更快速、更高效)和git
#验证版本
node -v
pnpm -v
git -v
使用creat-next-app脚手架创建项目一步到位
#--yes 使用保存的偏好设置或默认选项来跳过"Would you like to use the recommended Next.js defaults?"提示
#@latest表示显式指定最新版本
#用pnpm创建
pnpm create next-app@latest 项目名 --yes
#用npm创建
npx create-next-app@latest 项目名 --yes
#用yarn创建
yarn create next-app@latest 项目名 --yes
#用bun创建
bun create next-app@latest viora-learning --yes
也可以选择自定义
#用pnpm创建
pnpm create next-app
#用npm创建
npx create-next-app@latest
#用yarn创建
yarn create next-app
#用bun创建
bun create next-app
What is your project named? 项目名
Would you like to use the recommended Next.js defaults?
Yes, use recommended defaults - TypeScript, ESLint, No React Compiler, Tailwind CSS, No src/ directory, App Router, Cache Components, AGENTS.md
No, reuse previous settings
No, customize settings - Choose your own preferences
如果你选择了yes,它会自动下载官方推荐的配置
即TypeScript, ESLint, No React Compiler, Tailwind CSS, No src/ directory, App Router, Cache Components, AGENTS.md
如果你选择了 No, customize settings
就会出现让你自定义项,这里按需选择即可,比如选typescript和biome taulwind css什么的
Would you like to use TypeScript? No / Yes
Which linter would you like to use? ESLint / Biome / None
Would you like to use React Compiler? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like your code inside a `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to use Cache Components? No / Yes
Would you like to customize the import alias (`@/*` by default)? No / Yes
What import alias would you like configured? @/*
Would you like to include AGENTS.md to guide coding agents to write up-to-date Next.js code? No / Yes
手动安装(了解即可,因为自动安装会为我们配置这些东西)
如果你不想一步到位,而是自己做一遍,可以看如下过程
例如安装next react和react-dom
pnpm i next@latest react@latest react-dom@latest
然后再package.json中补充命令
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
}
}
app文件夹
然后我们在项目里创建一个app文件夹,里面新建两个文件--- page.tsx和 layout.tsx
Next.js 采用文件系统路由机制,这意味着应用程序中的路由路径取决于文件的排列方式,
如下是 App Router 规定的特殊文件(File Conventions)
| 文件名 | Next.js 赋予的职责 |
|---|---|
page.tsx | 页面入口 |
layout.tsx | 页面布局 |
loading.tsx | 加载界面 |
error.tsx | 错误界面 |
not-found.tsx | 404 界面 |
route.ts | API 路由处理程序 |
例如
app/
├── layout.tsx
├── page.tsx
├── about/
│ └── page.tsx
└── plugins/
├── page.tsx
└── layout.tsx
对应关系:
app/page.tsx→/app/about/page.tsx→/aboutapp/plugins/page.tsx→/plugins
layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
这里先接收界面上的react组件然后以html形式返回
//JavaScript 的对象解构和 TypeScript 类型声明
{
children,
}: {
children: React.ReactNode
}
page.tsx
page.tsx本身就是一个React 组件,这里会被layout.tsx识别到然后渲染成html
export default function Home() {
return(
<div>
<h1>Welcome to the Home Page</h1>
</div>
)
}
然后启动pnpm dev,它会自动安装typescript的依赖然后启动本地服务器,
Next.js 内置支持 TypeScript 语言。要将 TypeScript 引入到你的项目中,只需将文件重命名为
.ts/.tsx,然后运行next dev命令。Next.js 会自动安装所需的依赖库,并生成一个包含推荐配置选项的tsconfig.json文件
可以看到当前的page.tsx确实是在根目录的路由/
public文件夹
我们可以在根目录下创建一个 public 文件夹,用于存放静态资源,如图片、字体等。 public 文件夹中的文件可以通过基础 URL( / )在代码中进行引用
例如
import Image from 'next/image';
export default function Home() {
return(
<div>
<h1>Welcome to the Home Page</h1>
{/* <img src="/deepseek.png" width="200" alt="DeepSeek" /> */}
<Image src="/deepseek.png" alt="DeepSeek" width="200" height="200" loading="eager"/>
</div>
)
}
VScode的settings.json配置
我们在vscode的配置文件添加如下内容,用于解决用来解决 Next.js App Router 项目里 page.tsx、layout.tsx 等同名文件太多、标签页分不清的问题
"workbench.editor.customLabels.patterns": {
"**/app/**/page.tsx": "${dirname(1)}/${dirname} - page.tsx",
"**/app/**/layout.tsx": "${dirname(1)}/${dirname} - layout.tsx",
"**/app/**/loading.tsx": "${dirname(1)}/${dirname} - loading.tsx",
"**/app/**/error.tsx": "${dirname(1)}/${dirname} - error.tsx",
"**/app/**/not-found.tsx": "${dirname(1)}/${dirname} - not-found.tsx",
"**/app/**/template.tsx": "${dirname(1)}/${dirname} - template.tsx",
"**/app/**/default.tsx": "${dirname(1)}/${dirname} - default.tsx",
"**/app/**/route.ts": "${dirname(1)}/${dirname} - route.ts"
}
我们可以创建一个文件在这个路径app/dashboard/settings/page.tsx
![]() 配置前 |
![]() 配置后 |
代码检查功能
Next.js 支持使用 ESLint 或 Biome 进行代码检查
可以选择合适的代码检查工具,并通过 package.json 脚本直接执行检查操作
ESLint
#pnpm
pnpm add -D eslint eslint-config-next
#npm
npm i -D eslint eslint-config-next
#yarn
yarn add --dev eslint eslint-config-next
#bun
bun add -d eslint eslint-config-next
然后在根目录创建一个文件eslint.config.mjs,旧版是.eslintrc.*
填入nextjs官方推荐的参数
import { defineConfig, globalIgnores } from 'eslint/config'
import nextVitals from 'eslint-config-next/core-web-vitals'
const eslintConfig = defineConfig([
...nextVitals,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
]),
])
export default eslintConfig
然后修改package.json,补充命令
"scripts": {
"lint": "eslint",
"lint:fix": "eslint --fix"
}
运行的话就是pnpm lint或者pnpm run lint,没有输出就代表代码正常
然后eslint完全不支持typescript 7+,这个得等未来微软更新
所以目前有两种方案
① typescript版本降级到6(推荐)
pnpm add -D typescript@6.0
② eslint使用6,我们自己用7
pnpm add -D typescript@npm:@typescript/typescript6 @typescript/native@npm:typescript@^7.0.2
Biome
这个并不会和eslint冲突,影响的只是script的命令名字表示方式
biome的速度更快更现代,eslint生态更丰富插件更多,不过二者选一个即可,因为二者格式化的标准不太一样
#pnpm
pnpm add -D -E @biomejs/biome
#npm
npm i -D -E @biomejs/biome
#yarn
yarn add -D -E @biomejs/biome
#bun
bun add -D -E @biomejs/biome
然后初始化生成biome.json
#pnpm
pnpm biome init
#npm
npx biome init
#yarn
yarn biome init
#bun
bunx biome init
文件内容为
{
"$schema": "https://biomejs.dev/schemas/2.6.4/schema.json",
"vcs": {
"enabled": false,
"clientKind": "git",
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": false
},
"formatter": {
"enabled": true,
"indentStyle": "tab"
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended"
}
},
"javascript": {
"formatter": {
"quoteStyle": "double"
}
},
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on"
}
}
}
}
从eslint快速迁移到biome,此时这个biome.json文件会继承eslint的配置
#pnpm
pnpm biome migrate eslint --write
#npm
npx @biomejs/biome migrate eslint --write
#yarn
yarn biome migrate eslint --write
#bun
bunx biome migrate eslint --write
此时我们需要在根目录制作一个.gitignore文件,写入如下内容
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
并在终端运行git初始化
git init
然后我们还需要修改这个文件,只需要改vcs即可,因为我们的.gitignore文件已经把这些文件添加到排除项了
//vcs,即VCS (Version Control System,版本控制系统),也就是git版本控制,这里的useIgnoreFile表示忽略对.gitignore内声明排除git上传的文件或文件夹的biome检查
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
//files.includes为全局文件边界,控制 Formatter、Linter、Assist 的共同扫描范围,排除生成文件
//include强制忽略nextjs的 .next out build等文件夹内部的文件的检查 , !!表示强制忽略
//当然vcs内部属性都设置为true的话(前提是你的.gitignore文件排除掉了这些文件和文件夹)
//include可以不加或者删掉
"files": {
"ignoreUnknown": false,
"includes": ["**", "!!**/.next", "!!**/out", "!!**/build", "!next-env.d.ts"]
},
//linter.includes为lint检查的专属边界,只在确实需要额外排除某些 Lint 文件时使用
//linter原本的include排除项源于eslint的迁移,存在重复项,不过不改也没什么问题
//同样的, vcs内部属性都设置为true的话(前提是你的.gitignore文件排除掉了这些文件和文件夹),include可以直接删掉
//"includes": [
// "**",
// "!.next/**",
// "!out/**",
// "!build/**",
// "!next-env.d.ts",
// "!.next/**",
// "!out/**",
// "!build/**",
// "!next-env.d.ts"
// ]
"includes": ["**", "!.next/**", "!out/**", "!build/**", "!next-env.d.ts"]
迁移完成后删除eslint 和 eslint-config-next并手动删掉刚才创建的eslint.config.mjs文件
#pnpm
pnpm remove eslint eslint-config-next
#npm
npm uninstall eslint eslint-config-next
#yarn
yarn remove eslint eslint-config-next
#bun
bun remove eslint eslint-config-next
然后我们还需要在根目录创建.vscode文件夹,里面创建一个settings.json文件
之所以这么做的原因是你可能装了各种各样的格式化插件,但是不希望在本项目以外的地方使用biome,也不想改VScode的settings.json
此时就可以用这个局部设置,在我们保存文件的时候自动用biome格式化
{
"editor.formatOnSave": true,
"[javascript]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[javascriptreact]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[typescript]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[typescriptreact]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[json]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[jsonc]": {
"editor.defaultFormatter": "biomejs.biome"
},
"editor.codeActionsOnSave": {
"source.fixAll.biome": "explicit",
"source.organizeImports.biome": "explicit"
}
}
此时前往package.json添加和修改命令
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "biome check",
"lint:fix": "biome check --write",
"format": "biome format --write",
"typecheck": "tsc --noEmit"
},
然后打开终端运行根据需求运行如下命令即可
# 检查
pnpm lint
# 统一格式
pnpm format
# 再次检查
pnpm lint
# TypeScript 类型检查
pnpm typecheck
# 生产构建
pnpm build
设置 Absolute Imports 以及模块路径别名
虽然可以在page.tsx中使用import { Button } from "../components/Button";引入组件,但是如果项目变复杂了就
可能变成了类似import { Button } from "../../../components/Button";这种结构,无法分辨出它引入的是哪个哪个路径的组件,其次就是路径可能会输错
路径别名(Path Aliases)可以解决这个问题
// Before
import { Button } from '../../../components/button'
// After
import { Button } from '@/components/button'
@ 不是 Next.js 强制规定的特殊符号,而是路径别名(path alias)的前缀,也可以替换成其他符号或者单词
要配置绝对导入路径,需要在 tsconfig.json 或 jsconfig.json 文件中添加 baseUrl 配置选项,例如
在tsconfig.json中配置
baseUrl:定义模块查找的基础目录(此属性在typescript 7后被移除,在我们当前的typescript 6会警告)
paths:定义具体的路径别名映射规则,本质上是一个映射表,左边是你在import里写的模式, 右边是实际要去查找的路径列表,如果不写baseUrl的话必须写成完整相对路径
为了更直观的看出这个路径别名的作用,这里让chatgpt写两个示例,仅作对这个别名机制的理解,不需要理解代码
示例一(单层)
当前用一个简单示例
test
├── app/
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├──node_modules/
├── components/
│ └── HomeMessage.tsx
├── public/
│ └── deepseek.png
├── biome.json
├── next-env.d.ts
├── package.json
├── pnpm-lock.yaml
└── tsconfig.json
tsconfig.json
我们首先在tsconfig.json 中引入paths,定义@/ 为 根目录 ./
如果你使用自动安装的方式打开这个文件就会发现nextjs官方也是用这个方式定义项目根目录的
"." 指的就是 tsconfig.json 文件所在的目录 ,因为通常tsconfig.json放到根目录所以通常理解为"."就是根目录
| 配置 | 含义 |
|---|---|
@/* | 匹配以 @/ 开头的导入路径 |
* | 匹配后面的任意路径,即* 就是匹配任意后续字符串(含 /) |
// . 代表的是根目录,
"compilerOptions": {
"paths": {
//这里如果要放到src文件内的话就是 "@/*": ["./src/*"]
"@/*": ["./*"]
}
},
page.tsx
可以看到我们可以用@/代表根目录./
import Image from "next/image";
import HomeMessage from "@/components/HomeMessage";
export default function Home() {
return (
<div>
<h1>Welcome to the Home Page</h1>
<Image
src="/deepseek.png"
alt="DeepSeek"
width={200}
height={200}
loading="eager"
/>
<HomeMessage />
</div>
);
}
layout.tsx
这个和之前一样,不过引入了css样式
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "My Project",
description: "Path alias demonstration",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN">
<body>{children}</body>
</html>
);
}
globals.css
做一些公共样式
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 40px;
font-family: Arial, sans-serif;
}
h1 {
margin-bottom: 20px;
}
h2 {
margin-top: 20px;
}
HomeMessage.tsx
我们随便做一个组件
export default function HomeMessage() {
return (
<div>
<h2>Hello, this is HomeMessage!</h2>
<p>This component is located in the components directory.</p>
</div>
);
}
示例二(多层,且根路径src)
test
├── src/
│ ├── app/
│ │ ├── globals.css
│ │ ├── layout.tsx
│ │ └── page.tsx
│ ├── components/
│ │ ├── HomeMessage.tsx
│ │ └── ui/
│ │ └── Button.tsx
│ ├── features/
│ │ └── home/
│ │ └── HeroSection.tsx
│ └── lib/
│ └── utils/
│ └── format.ts
├── public/
│ └── deepseek.png
├── biome.json
├── next-env.d.ts
├── package.json
├── pnpm-lock.yaml
└── tsconfig.json
tsconfig.json
此时就是
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
page.tsx
import Image from "next/image";
import HomeMessage from "@/components/HomeMessage";
import HeroSection from "@/features/home/HeroSection";
import { formatTitle } from "@/lib/utils/format";
export default function Home() {
const title = formatTitle("Welcome to the Home Page");
return (
<div>
<h1>{title}</h1>
<Image
src="/deepseek.png"
alt="DeepSeek"
width={200}
height={200}
loading="eager"
/>
<HomeMessage />
<HeroSection />
</div>
);
}
layout.tsx
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "My Project",
description: "Path alias demonstration with src directory",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN">
<body>{children}</body>
</html>
);
}
globals.css
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 40px;
font-family: Arial, sans-serif;
}
h1 {
margin-bottom: 20px;
}
h2 {
margin-top: 20px;
}
.primary-button {
padding: 8px 16px;
border: 1px solid #333;
background: #fff;
cursor: pointer;
}
Button.tsx
import type { ReactNode } from "react";
type ButtonProps = {
children: ReactNode;
onClick?: () => void;
};
export default function Button({ children, onClick }: ButtonProps) {
return (
<button className="primary-button" onClick={onClick}>
{children}
</button>
);
}
HomeMessage.tsx
import Button from "@/components/ui/Button";
export default function HomeMessage() {
return (
<div>
<h2>Hello, this is HomeMessage!</h2>
<p>This component is located in the src/components directory.</p>
<Button>Click me</Button>
</div>
);
}
HeroSection.tsx
import Button from "@/components/ui/Button";
import { formatTitle } from "@/lib/utils/format";
export default function HeroSection() {
const title = formatTitle("多层目录别名示例");
return (
<section>
<h2>{title}</h2>
<p>
这个组件位于 <code>src/features/home</code>,导入时使用 <code>@/</code>{" "}
指向 <code>src</code>
</p>
<Button>开始使用</Button>
</section>
);
}
format.ts
export function formatTitle(title: string): string {
return title.trim().replace(/\s+/g, " ").toUpperCase();
}
更新nextjs
#pnpm
pnpm next upgrade
#npm
npx next upgrade
#yarn
yarn next upgrade
#bun
bunx next upgrade
自动安装下的相关配置
默认安装下会自动配置这四个命令
"scripts": {
"dev": "next dev", #开发模式启动 Next.js
"build": "next build", #构建用于生产环境的应用程序
"start": "next start", #启动 Next.js 生产环境服务器
"lint": "eslint" #设置 Next.js 的内置 ESLint 配置
},
刚才并没有说这个,这里补充一下命令的运行
这个取决你用什么安装的这个项目,如果是用npx(npm)安装就是npm run dev, 如果是pnpm就是pnpm run dev或pnpm dev,依此类推
其实这个可以自定义,把scripts里的dev 改成 D 也是可以的, 因为真正起作用的是next dev,表示在http://localhost:3000启动本地服务器
这个推荐使用chrome的无痕模式(ctrl +shift +N)打开网页或者用vscode内置浏览器,避免浏览器插件干扰
目前的默认的结构就是如下,如果你看了上述的手动安装的过程就知道这些文件的含义和作用
viora-learning/
├── app/
│ ├── favicon.ico
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├── node_modules/
├── public/
├── AGENTS.md
├── README.md
├── eslint.config.mjs
├── next-env.d.ts
├── next.config.ts
├── package.json
├── pnpm-lock.yaml
├── pnpm-workspace.yaml
└── tsconfig.json






