Files
cs-note/hhs/REACT/1. 基础篇/01-环境搭建与项目结构.md
T
2026-05-24 11:42:38 +08:00

219 lines
6.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
tags: [React, TypeScript, Frontend, Vite]
create time: 2026-04-29 22:00
---
# 环境搭建与项目结构
## 概述
本文档作为 React 开发系列的起点,介绍从零搭建 **React + TypeScript** 开发环境的全过程。内容包括:主流脚手架工具的选型对比、Vite 项目初始化与核心配置、推荐的目录结构与文件命名规范。完成本章后,你将拥有一个开箱即用的工程化项目骨架,为后续学习组件开发、状态管理和路由打下基础。
> [!tip] 前置知识
> - 已安装 **Node.js 18+**(推荐 LTS 版本)
> - 熟悉基本的终端操作和 npm 命令
> - 了解 JavaScript/TypeScript 基本语法
## 选型决策:Vite vs CRA vs Next.js
> [!question] 思考:为什么不再推荐使用 Create React App?
Create React App 已经停止维护,其 Webpack 构建在大型项目中存在明显的冷启动慢、HMR 速度慢等问题。以下是三种方案的横向对比:
```mermaid
graph TD
A[项目类型] --> B["纯 SPA"]
A --> C["SSR / 全栈应用"]
B --> D[Vite + React]
C --> E[Next.js App Router]
D --> F["适合场景:前端主导、后端提供 API"]
E --> G["适合场景:SEO 优先、服务端渲染需求"]
style D fill:#61DAFB,color:#000
style E fill:#000
```
### Vite 方案(本文档主推)
Vite 基于原生 ES Modules + esbuild,实现毫秒级热更新。相比传统的 Webpack 方案,开发服务器启动时间从数十秒降至亚秒级。
```bash
# 创建项目(选择 react-ts 模板)
npm create vite@latest my-app -- --template react-ts
cd my-app
# 安装依赖
npm install
# 启动开发服务器(自动打开浏览器)
npm run dev
```
### Vite 核心配置
`vite.config.ts` 是开发服务器的中枢,通常需要配置路径别名、代理和插件:
```ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from 'path'
export default defineConfig({
plugins: [react()], // SWC 编译器比 Babel 更快
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'), // @ 别名指向 src 目录
},
},
server: {
proxy: {
'/api': 'http://localhost:8080', // 开发时代理后端请求
},
},
})
```
> [!note] 关键配置说明
> - **SWC vs Babel**:`@vitejs/plugin-react-swc` 使用 Rust 编写的 SWC 编译器,编译速度显著优于传统 Babel 方案
> - **路径别名**:配合 `tsconfig.json` 中的 `paths` 配置,可以消除项目中深层的相对导入(`../../../utils` → `@/utils`)
> - **代理**:本地开发时将 `/api` 开头的请求转发到后端服务,避免跨域问题
### Next.js 方案
```bash
# --app: 使用 App Router(推荐)
# --typescript: 启用 TypeScript
# --tailwind: 集成 Tailwind CSS
# --src-dir: 代码放在 src 目录
npx create-next-app@latest my-app --typescript --app --tailwind --src-dir
```
> [!warning] 选型建议
> - 如果你的项目以 **SEO、首屏加载速度、全栈能力** 为核心需求,选 Next.js
> - 如果团队更擅长 **纯前端开发**,后端由独立 API 服务提供,Vite + React 是更轻量合理的选择
## 目录结构
### 标准组织方式
推荐的 React + TypeScript 项目目录结构如下:
```
src/
├── assets/ # 静态资源(图片、字体等)
├── components/ # 通用 UI 组件(无状态或低状态)
│ ├── Button/
│ │ ├── Button.tsx
│ │ ├── Button.test.tsx
│ │ └── index.ts
│ └── Modal/
├── hooks/ # 自定义 Hooks
├── pages/ # 页面级组件
├── routes/ # 路由配置
├── stores/ # 状态管理(Zustand / Redux)
├── types/ # TypeScript 类型定义
├── utils/ # 工具函数
├── App.tsx # 根组件
└── main.tsx # 入口文件
```
### 模块依赖关系
理解各目录之间的引用关系对维护项目至关重要:
```mermaid
graph LR
MAIN[main.tsx] --> APP[App.tsx]
APP --> PAGES[pages - 页面组件]
APP --> ROUTES[routes - 路由配置]
PAGES --> COMPONENTS[components - UI组件]
PAGES --> HOOKS[hooks - 自定义Hooks]
PAGES --> STORES[stores - 状态管理]
COMPONENTS --> HOOKS
COMPONENTS --> UTILS[utils - 工具函数]
COMPONENTS --> TYPES[types - 类型定义]
STORES --> TYPES
ROUTES --> PAGES
```
> [!note] 依赖方向原则
> - **单向依赖**:上层模块(pages/stores)依赖下层模块(components/hooks/utils),反向依赖会导致循环引用
> - **types 是基础设施**:被所有层共享,但绝不反过来依赖其他业务模块
> [!tip] 目录组织原则
> - **按功能而非按类型**:大型项目推荐使用 Feature-Sliced Design 或 Atomics 模式,将组件、Hook、样式、测试放在同一目录下
> - **Barrel Export(统一导出)**:每个子目录通过 `index.ts` 导出统一接口,简化上游 import 路径
## 关键配置文件
### tsconfig.json 核心选项
```jsonc
{
"compilerOptions": {
"target": "ES2020", // 目标 JS 版本
"module": "ESNext", // 模块系统
"jsx": "react-jsx", // React 17+ 自动导入 JSX transform
"strict": true, // 开启严格模式
"baseUrl": ".",
"paths": {
"@/*": ["src/*"] // 路径别名
}
}
}
```
### ESLint + Prettier 组合
推荐使用 **ESLint flat config**(`eslint.config.js`),这是 ESLint 9 引入的新格式:
```js
// eslint.config.js (flat config)
import js from '@eslint/js'
import tseslint from 'typescript-eslint'
import reactHooks from 'eslint-plugin-react-hooks'
import globals from 'globals'
export default tseslint.config(
js.configs.recommended,
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: { ...globals.browser },
},
plugins: {
'react-hooks': reactHooks,
},
rules: {
...reactHooks.configs.recommended.rules,
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
}
)
```
> [!tip] ESLint 迁移提示
> - 旧版 `.eslintrc.*` 格式的配置文件可以通过 `eslint --init` 自动迁移为 flat config
> - `@typescript-eslint` 同时接管了 TypeScript 特有规则和 JavaScript 规则,无需再单独安装 `eslint-plugin-typescript`
> - React 19 的 ESLint 插件正在逐步推出新特性,建议保持版本同步更新
## 开发习惯建议
| 工具 | 用途 | 推荐版本 |
|------|------|----------|
| Vite | 构建 & HMR | ^6.x |
| TypeScript | 类型安全 | ^5.x |
| ESLint | 代码质量 | ^9.x (flat config) |
| Prettier | 格式化 | ^3.x |
| Vitest | 单元测试 | ^3.x |
## 关联笔记
- [[hhs/REACT/README]]
- [[hhs/REACT/1. 基础篇/02-JSX 语法]]
- [[hhs/REACT/3. 生态工具篇/08-路由管理]]
- [[hhs/REACT/5. 工程实践篇/16-测试]]