2026-01-28-Next.js初上手

文章发布时间:

最后更新时间:

页面浏览: 加载中...

Next.js 官网:https://nextjs.org/
Next.js 官方文档:https://nextjs.org/docs
Github 源码:https://github.com/vercel/next.js

0x00 Next.js:React 开发框架

alt text

Next.js是一个 React 开发框架,用于构建 React 应用程序用,特性如下:

  • 文件系统路由: Next.js 使用文件系统来自动化路由的创建。你只需要在 pages 目录下创建文件,它就会自动映射为相应的路由,不需要额外的路由配置。
  • 静态生成(SSG)与服务端渲染(SSR): Next.js 支持这两种渲染方式,可以根据需要灵活选择。静态生成适用于大多数情况,尤其是内容不会频繁变化的页面,而 SSR 适用于需要动态获取数据的页面。
  • API 路由: Next.js 允许你在应用中直接创建 API 路由,可以在 pages/api 目录下轻松创建后端 API 端点,处理前后端逻辑。
  • 自动代码拆分: 每个页面只会加载它所需的 JavaScript 代码,确保应用启动速度更快,减少不必要的资源消耗。
  • 优化图片: Next.js 内置了图片优化功能,使用 next/image 组件可以自动为图像选择最佳格式、压缩、懒加载等,以提升页面加载性能。
  • 支持 TypeScript: Next.js 默认支持 TypeScript,可以让开发者在开发过程中享受更强的类型检查。

反正前端找工作不得不学…


0x01 创建Next.js项目及相关配置

项目初建

在Webstrom中利用脚手架先创建项目:

alt text

过程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
C:\nvm4w\nodejs\npx.cmd --yes create-next-app"@latest" . --ts

√ 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 customize the import alias (`@/*` by default)? ... No / Yes
√ What import alias would you like configured? ... @/*
Creating a new Next.js app in E:\TsetRange9\next_0128.

Using npm.

Initializing project with template: app-tw


Installing dependencies:
- next
- react
- react-dom

Installing devDependencies:
- @tailwindcss/postcss
- @types/node
- @types/react
- @types/react-dom
- babel-plugin-react-compiler
- eslint
- eslint-config-next
- tailwindcss
- typescript


added 357 packages in 28s

141 packages are looking for funding
run `npm fund` for details

Generating route types...
✓ Types generated successfully

Initialized a git repository.

Success! Created next_0128 at E:\TsetRange9\next_0128

Done

过程中的一些交互式配置问题:

  • React Compiler:启用 React 官方的实验性编译器(优化性能)
  • Tailwind CSS:集成流行的原子化 CSS 框架,便于快速样式开发
  • src/ directory:将代码放在 src/ 文件夹中(推荐的结构化方式)
  • App Router:使用 Next.js 13+ 的新路由系统(基于 app/ 目录,推荐)
  • Import alias:配置路径别名(如 @/components),默认 @/*
  • 自动初始化 Git 仓库,并创建初始 commit
1
2
Success! Created next_0128 at E:\TsetRange9\next_0128
Done

项目创建成功后,接下来进入目录运行 npm run dev 启动开发服务器
http://localhost:3000

alt text

代码质量工具ESlint,Stylelint,Prettier和CommitLint

关于ESlint

ESLint 是一个可配置的 JavaScript 检查器。它可以帮助你发现并修复 JavaScript 代码中的问题。问题可以指潜在的运行时漏洞、未使用最佳实践、风格问题等。

参考:ESLint 入门 - ESLint - 插件化的 JavaScript 代码检查工具
目前在脚手架中已经自动配置

创建项目后,目录下有文件 eslint.config.mjs,直接进行对应的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";

// TypeScript 官方 ESLint 配置与解析器
import tseslint from "typescript-eslint";
// 关闭与 Prettier 冲突的 ESLint 规则集合
import prettierConfig from "eslint-config-prettier";
// 让 ESLint 直接报告 Prettier 格式问题的插件
import prettierPlugin from "eslint-plugin-prettier";
// 检测并可自动移除未使用 import 的实用插件
import unusedImportsPlugin from "eslint-plugin-unused-imports";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const compat = new FlatCompat({
baseDirectory: __dirname, // 用于解析相对路径的基准目录
});

// 导出 ESLint 平面配置
export default tseslint.config(
// 引入 Next.js 官方推荐的核心规则集(包含 React、Core Web Vitals 等)
...compat.extends("next/core-web-vitals", "next/typescript"),

// 引入 TypeScript 官方推荐规则(包含 parser 和基础类型检查规则)
...tseslint.configs.recommended,

// 自定义插件与规则区域
{
// 注册使用的插件
plugins: {
prettier: prettierPlugin, // 集成 Prettier 检查
"unused-imports": unusedImportsPlugin, // 未使用导入检测与清理
},

// 自定义规则:覆盖默认行为或添加项目特定规则
rules: {
// 在 Next.js + TS 项目中这两个 import 规则常误报,关闭
"import/default": 0,
"import/no-named-as-default-member": 0,

// 关闭原生 no-unused-vars,改用 TS 专用版本以更好支持 type-only imports
"no-unused-vars": "off",

// Next.js App Router 模式下不再需要显式 import React
"react/react-in-jsx-scope": "off",

// 允许使用 @ts-ignore / @ts-expect-error 等注释(可根据团队规范调整)
"@typescript-eslint/ban-ts-comment": "off",

// 检测到未使用的 import 时给出警告(配合 --fix 可自动删除)
"unused-imports/no-unused-imports": "warn",

// React + TS 项目依靠 TypeScript 类型检查,无需 prop-types
"react/prop-types": "off",

// 将 Prettier 格式问题视为 ESLint 错误(强制代码风格一致)
"prettier/prettier": "error",

// 允许 console 但给出警告(开发阶段方便,CI 可升级为 error)
"no-console": "warn",

// TypeScript 专用的未使用变量检查(更精准,支持 _ 前缀忽略)
"@typescript-eslint/no-unused-vars": "warn",

// 对 any 类型仅警告而非报错(适合逐步减少 any 的过渡阶段)
"@typescript-eslint/no-explicit-any": "warn",
},
},

// Prettier 冲突规则关闭集合
prettierConfig,

// 这些文件/目录不会被 ESLint 检查
{
ignores: [
".next/**", // Next.js 编译输出目录
"out/**", // 静态导出目录
"build/**", // 其他可能的构建目录
"next-env.d.ts", // Next.js 自动生成的类型声明文件
"node_modules/**", // 依赖目录
"**/*.mjs", // 纯 ESM 工具文件(视项目需要)
"**/*.min.js", // 已压缩的文件
],
},
);

关于Stylelint

Stylelint 是一个强大、先进的 CSS 代码检查器(linter),可以帮助规避 CSS 代码中的错误并保持一致的编码风格。

安装 Stylelint 并创建配置:

1
2
npm install --save-dev stylelint stylelint-config-standard stylelint-order stylelint-config-recess-order postcss-html
npm install --save-dev stylelint-config-standard-scss

在项目根目录下创建 .stylelintrc.mjs 文件,并添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/** @type {import('stylelint').Config} */
export default {
extends: [
// 基础配置 (包含了 CSS Modules 和 现代 CSS 特性检查)
"stylelint-config-standard",
// 如果你使用 SCSS,取消下面这行的注释,并注释掉上面那行
// "stylelint-config-standard-scss",
// 属性自动排序
"stylelint-config-recess-order",
],

// 针对不同文件类型的特定覆盖
overrides: [
{
files: ["**/*.{html,vue}"],
customSyntax: "postcss-html",
},
{
files: ["**/*.{jsx,tsx}"],
customSyntax: "postcss-styled-syntax", // 如果使用 CSS-in-JS }
],

rules: {
// 1. 强制使用现代颜色函数 (如 oklch, lab, 或逗号分隔的 rgb 新语法)
"color-function-notation": "modern",

// 2. 透明度使用百分比写法 (opacity: 50% 而不是 0.5) "alpha-value-notation": "percentage",

// 3. 限制选择器特异性 (防止嵌套过深,配合原生 CSS Nesting) "selector-max-specificity": "0,4,0",
"max-nesting-depth": 3,

// 4. 强制使用伪元素双冒号 (::before 而不是 :before) "selector-pseudo-element-colon-notation": "double",

// 5. 禁止未知的伪类 (兼容未来的 CSS 伪类)
"selector-pseudo-class-no-unknown": [
true,
{
ignorePseudoClasses: ["global", "deep", "slotted"],
},
],

/* ------------------------------------------------
逻辑属性 (Logical Properties)
强制使用 margin-inline-start 而非 margin-left
------------------------------------------------ */
// 6. 禁止空的代码块
"block-no-empty": true,

// 7. 自定义类名模式 (BEM 或 Kebab-case) "selector-class-pattern": [
"^[a-z]([a-z0-9-]+)?(__([a-z0-9]+))?(--([a-z0-9]+))?$",
{
message: "Expected class selector to be BEM pattern",
},
],

/* ------------------------------------------------
与 Prettier 的兼容
------------------------------------------------ */
// "comment-empty-line-before": null,
},

// 忽略文件
ignoreFiles: ["dist/**/*", "node_modules/**/*", "**/*.min.css"],
};

在项目根目录下创建 .stylelintignore 文件,并添加以下内容:

1
2
3
coverage
node_modules
//其他要忽略的内容,比如引入tailwindcss那个

格式化工具prettier

在前端工程化项目( React、Next.js、TypeScript 等大型团队项目)中,Prettier 被广泛用于强制代码格式一致性,避免风格争议。它是“opinionated”(有主见)的格式化工具,通常与 ESLint 结合使用(通过 eslint-config-prettier 关闭冲突规则),并通过 Husky + lint-staged 在 git commit 前自动格式化。

opinionated(主见性): 工具开发者预设了一套强烈的、特定的最佳实践和规则,用户配置选项较少,必须遵循这些预设方式

作为代码质量工具,会移除所有原始样式,并确保所有输出的代码符合一致的风格

安装

1
npm install --save-dev --save-exact prettier

创建一个空的配置文件

1
node --eval "fs.writeFileSync('.prettierrc.json','{}\n')"

创建一个 .prettierignore 文件,让 Prettier CLI 和编辑器知道哪些文件不需要格式化

1
node --eval "fs.writeFileSync('.prettierignore','# Ignore artifacts:\nbuild\ncoverage\n')"

运行

1
2
npx prettier . --check
npx prettier . --write

--check 类似于 --write,但仅检查文件是否已格式化,而不是覆盖它们。prettier --writeprettier --check 是运行 Prettier 的最常见方法。

将格式化工具与编辑器集成参考: https://prettier.node.org.cn/docs/en/watching-files

alt text

关于CommitLint

commitlint 是一个专为 Git 提交信息设计的语义化校验引擎,它通过可配置的规则集确保提交信息符合预定义的规范。

安装 commitlint 及其核心依赖:

1
npm install -D @commitlint/cli @commitlint/config-conventional
  • @commitlint/cli:命令行工具,负责解析参数和执行校验流程
  • @commitlint/config-conventional:内置的 Conventional Commits 规范配置集

创建commitlint配置commitlint.config.js

1
2
3
4
// commitlint.config.js
module.exports = {
extends: ["@commitlint/config-conventional"],
};

husky 与自动化提交检查

husky 是一个专为现代前端项目设计的 Git 钩子管理系统,它解决了传统 Git 钩子管理的诸多痛点

初始化:

1
npx husky init

这一步会创建 .husky 目录

安装 lint-staged来只检查暂存区的文件:

1
npm install --save-dev lint-staged

package.json 添加脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint . && stylelint **/*.{css,scss,less}",
"lint:css": "stylelint **/*.{css,scss,less}",
"lint:css:fix": "stylelint --fix **/*.{css,scss,less}",
"lint:fix": "eslint . --fix && stylelint **/*.{css,scss,less} --fix",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md,css}\"",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,md,css}\"",
"prepare": "husky",
"commitlint": "commitlint --edit",
"precommit": "lint-staged"
},

结合 Husky + lint-staged(commit 前自动修复):
package.json中添加 lint-staged配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint . && stylelint **/*.{css,scss,less}",
"lint:css": "stylelint **/*.{css,scss,less}",
"lint:css:fix": "stylelint --fix **/*.{css,scss,less}",
"lint:fix": "eslint . --fix && stylelint **/*.{css,scss,less} --fix",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md,css}\"",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,md,css}\"",
"prepare": "husky",
"commitlint": "commitlint --edit",
"precommit": "lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{css,scss,less}": [
"stylelint --fix",
"prettier --write"
],
"*.{json,md}": [
"prettier --write"
]
}
}

配置自动化提交检查:在 .husky 目录中, pre-commitcommit-msg 钩子应该配置如下:(没有则创建)

0

1
2
#pre-commit
npx --no-install commitlint --config commitlint.config.js --edit $1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/sh
# commit-msg
. "$(dirname "$0")/_/husky.sh"
echo "开始代码检查..."

# 运行 lint-staged
npx lint-staged

# 检查执行结果
if [ $? -ne 0 ]; then
  echo "代码检查未通过,请修复错误后重新提交"
  exit 1
fi

echo "代码检查通过"

配置后,在提交前会:

  • 运行 ESLint 检查 JavaScript/TypeScript
  • 运行 Stylelint 检查 CSS/SASS/LESS
  • 运行 Prettier 格式化代码
  • 只检查暂存区的文件,提高效率
  • 自动修复可自动修复的问题,会重新提示暂存文件

在commitlint.config.js中配置的@commitlint/config-conventional,提交信息应该符合Conventional Commits规范,格式为:

1
2
3
<type>(<scope>): <subject>
<body>
<footer>

其中,type是提交的类型,必须是以下之一:

  • feat: 新功能
  • fix: 修复bug
  • docs: 文档更新
  • style: 代码格式调整(不影响代码运行)
  • refactor: 重构
  • test: 测试相关
  • chore: 构建过程或辅助工具的变动

例如,一个简单的提交信息:

1
feat: 添加用户登录功能

我们也可以自定义type Configuration | commitlint


devtools

参考