React 环境配置
本章节将介绍如何搭建 React 开发环境,包括使用框架快速启动项目和从零开始构建。
环境要求
在开始之前,请确保你的电脑上安装了以下软件:
- Node.js:推荐 v18.0.0 或更高版本(React 18+ 需要)
- npm 或 yarn 或 pnpm:包管理器
- 代码编辑器:推荐 VS Code
检查 Node.js 版本
打开终端或命令行工具,输入以下命令检查 Node.js 是否已安装:
node --version
npm --version
如果显示了版本号,说明 Node.js 已安装。React 19 建议使用 Node.js 18.0.0 或更高版本。
选择项目创建方式
React 官方推荐根据你的需求选择不同的创建方式:
| 需求 | 推荐方式 |
|---|---|
| 全栈应用、需要 SEO | Next.js |
| 单页应用、需要路由 | React Router v7 + Vite |
| 移动端应用 | Expo |
| 学习 React 基础 | Vite |
| 完全自定义 | 从零开始 |
方式一:使用 Next.js(推荐)
Next.js 是一个 React 全栈框架,支持服务端渲染(SSR)、静态生成(SSG)和 API 路由。它的 App Router 完全实现了 React Server Components 规范。
创建项目
# 创建 Next.js 项目
npx create-next-app@latest
# 或者指定项目名
npx create-next-app@latest my-next-app
创建过程中会询问以下配置选项:
What is your project named? my-next-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? 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? No / Yes
Would you like to use Turbopack for `next dev`? No / Yes
Would you like to customize the import alias? No / Yes
项目结构
my-next-app/
├── app/ # App Router 目录
│ ├── layout.tsx # 根布局
│ ├── page.tsx # 首页
│ ├── globals.css # 全局样式
│ └── api/ # API 路由
├── public/ # 静态资源
├── next.config.js # Next.js 配置
├── package.json
└── tsconfig.json # TypeScript 配置(如果启用)
开发命令
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 启动生产服务器
npm run start
# 代码检查
npm run lint
Next.js 的优势
- 服务端渲染:更好的 SEO 和首屏加载性能
- React Server Components:减少客户端 JavaScript 体积
- 文件系统路由:基于文件结构自动生成路由
- API 路由:在同一项目中构建 API
- 图片优化:自动优化图片
- 内置 CSS 支持:支持 CSS Modules、Tailwind CSS
方式二:使用 React Router v7
React Router v7 可以与 Vite 配合,创建一个全栈 React 框架。它强调标准 Web API,并提供多种部署模板。
创建项目
# 创建 React Router 项目
npx create-react-router@latest
项目结构
my-router-app/
├── app/
│ ├── routes/ # 路由组件
│ ├── root.tsx # 根组件
│ └── layout.tsx # 布局组件
├── public/
├── package.json
└── vite.config.ts
React Router v7 的特点
- 标准 Web API:使用标准的 Request/Response 对象
- 多种运行时支持:支持 Node.js、Deno、Cloudflare Workers 等
- 数据加载:内置数据加载和提交机制
- 嵌套路由:支持复杂的路由嵌套
方式三:使用 Vite(学习推荐)
Vite 是一个现代化的前端构建工具,启动速度快,热更新迅速。非常适合学习 React 和构建单页应用。
创建项目
# 创建项目(使用 npm)
npm create vite@latest my-react-app -- --template react
# 创建 TypeScript 项目
npm create vite@latest my-react-app -- --template react-ts
# 进入项目目录
cd my-react-app
# 安装依赖
npm install
# 启动开发服务器
npm run dev
项目结构
my-react-app/
├── public/ # 静态资源
│ └── vite.svg
├── src/ # 源代码
│ ├── assets/ # 需要构建的资源
│ ├── App.jsx # 主组件
│ ├── App.css # 主组件样式
│ ├── index.css # 全局样式
│ └── main.jsx # 入口文件
├── index.html # HTML 模板
├── package.json # 项目配置
└── vite.config.js # Vite 配置
Vite 配置文件
vite.config.js 是 Vite 的配置文件:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
port: 3000, // 开发服务器端口
open: true, // 自动打开浏览器
host: true, // 允许局域网访问
},
build: {
outDir: 'dist', // 构建输出目录
sourcemap: true, // 生成 sourcemap
}
})
常用开发命令
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 预览生产构建
npm run preview
方式四:使用 Expo(移动端开发)
Expo 是一个 React 框架,用于创建跨平台的 Android、iOS 和 Web 应用。
创建项目
# 创建 Expo 项目
npx create-expo-app@latest
# 或指定项目名
npx create-expo-app@latest my-expo-app
开发命令
# 启动开发服务器
npx expo start
# 在 iOS 模拟器中运行
npx expo start --ios
# 在 Android 模拟器中运行
npx expo start --android
# 在 Web 浏览器中运行
npx expo start --web
Expo 的优势
- 跨平台:一套代码,同时运行在 iOS、Android 和 Web
- 原生 API:通过 SDK 轻松访问相机、通知等原生功能
- OTA 更新:无需重新发布应用即可更新
- 开发工具:Expo Go 应用可在真机上快速测试
环境变量配置
在 React 项目中,可以使用环境变量来管理不同环境的配置。
Vite 环境变量
Vite 使用 VITE_ 前缀的环境变量:
# .env.development
VITE_API_URL=http://localhost:3000/api
VITE_APP_TITLE=开发环境
# .env.production
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=生产环境
在代码中使用:
function App() {
const apiUrl = import.meta.env.VITE_API_URL;
const title = import.meta.env.VITE_APP_TITLE;
return (
<div>
<h1>{title}</h1>
<p>API 地址:{apiUrl}</p>
</div>
);
}
Next.js 环境变量
Next.js 使用 NEXT_PUBLIC_ 前缀暴露到客户端:
# .env.local
DATABASE_URL=postgresql://localhost:5432/mydb
# 暴露到客户端
NEXT_PUBLIC_API_URL=https://api.example.com
// 服务端和客户端都可以访问
const publicUrl = process.env.NEXT_PUBLIC_API_URL;
// 仅服务端可访问
const dbUrl = process.env.DATABASE_URL;
TypeScript 配置
如果你使用 TypeScript,需要对 React 项目进行配置。
安装类型定义
npm install -D typescript @types/react @types/react-dom @types/node
tsconfig.json 配置
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
文件扩展名
TypeScript React 文件使用 .tsx 扩展名:
// src/App.tsx
import { useState } from 'react';
interface AppProps {
title: string;
}
function App({ title }: AppProps) {
const [count, setCount] = useState<number>(0);
return (
<div>
<h1>{title}</h1>
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
</div>
);
}
export default App;
VS Code 开发工具配置
推荐扩展
- ES7+ React/Redux/React-Native snippets - React 代码片段
- Prettier - Code formatter - 代码格式化
- ESLint - 代码检查
- Auto Rename Tag - 自动重命名标签
- Tailwind CSS IntelliSense - Tailwind 类名提示(如果使用 Tailwind)
工作区配置
在项目根目录创建 .vscode/settings.json:
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"emmet.includeLanguages": {
"javascript": "javascriptreact"
},
"files.associations": {
"*.css": "css",
"*.jsx": "javascriptreact",
"*.tsx": "typescriptreact"
}
}
推荐扩展配置
创建 .vscode/extensions.json:
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"dsznajder.es7-react-js-snippets",
"formulahendry.auto-rename-tag"
]
}
ESLint 和 Prettier 配置
安装依赖
npm install -D eslint prettier eslint-plugin-react eslint-plugin-react-hooks eslint-config-prettier
ESLint 配置
创建 .eslintrc.cjs:
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
'prettier'
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
settings: { react: { version: '19.0' } },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
'react/prop-types': 'off'
},
}
Prettier 配置
创建 .prettierrc:
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
第一个 React 组件
无论使用哪种方式创建项目,你的第一个 React 组件通常如下:
函数组件
// src/App.jsx
import { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
return (
<div style={{ padding: '20px', textAlign: 'center' }}>
<h1>你好,React!</h1>
<p>欢迎开始学习 React 编程</p>
<button onClick={() => setCount(c => c + 1)}>
点击次数:{count}
</button>
</div>
);
}
export default App;
入口文件
// src/main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);
常见问题与解决方案
Node 版本过低
如果 Node.js 版本过低,建议使用 nvm(Node Version Manager)管理 Node.js 版本:
Windows(使用 nvm-windows):
# 安装 nvm-windows 后
nvm install 20
nvm use 20
macOS/Linux:
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 安装并使用 Node.js 20
nvm install 20
nvm use 20
npm 安装失败
# 清除 npm 缓存
npm cache clean --force
# 或使用 yarn 代替
npm install -g yarn
yarn install
# 或使用 pnpm(更快)
npm install -g pnpm
pnpm install
端口被占用
# Vite:修改 vite.config.js
server: {
port: 3001
}
# Next.js:使用 -p 参数
npm run dev -- -p 3001
热更新不工作
检查以下可能的原因:
- 文件是否在
src目录内 - 是否正确导入了 CSS 文件
- 浏览器是否禁用了缓存
- 是否使用了
export default
小结
本章我们学习了:
项目创建方式
- Next.js:全栈应用,支持 SSR 和 Server Components
- React Router v7:单页应用,强调标准 Web API
- Vite:学习和小型项目首选,启动快
- Expo:移动端跨平台开发
配置要点
- 环境变量的使用(
VITE_和NEXT_PUBLIC_前缀) - TypeScript 配置(
.tsx文件扩展名) - VS Code 扩展和配置
- ESLint 和 Prettier 代码规范
开发命令
npm run dev:启动开发服务器npm run build:构建生产版本npm run preview:预览生产构建
练习
- 使用 Vite 创建一个新的 React 项目,并修改首页显示你的名字
- 配置环境变量,在组件中显示不同环境的 API 地址
- 为项目添加 ESLint 和 Prettier 配置
- 尝试创建一个 Next.js 项目,比较与 Vite 项目的区别