React 安装
概述
本章将详细介绍如何搭建 React 开发环境,包括 Node.js 安装、开发工具配置、创建第一个 React 项目等内容。我们将学习多种创建 React 项目的方式,以及必要的开发工具安装。
🛠️ 前置要求
必需软件
Node.js 和 npm
bash
# 检查是否已安装 Node.js
node --version
# 应显示:v18.0.0 或更高版本
# 检查 npm 版本
npm --version
# 应显示:8.0.0 或更高版本推荐配置:
- Node.js 18.0+ 或 20.0+(LTS 版本)
- npm 8.0+ 或 yarn 1.22+
- 现代浏览器(Chrome、Firefox、Safari、Edge)
可选工具
- Git:版本控制
- VS Code:推荐的代码编辑器
- Chrome DevTools:调试工具
📥 Node.js 安装
Windows 系统
bash
# 方法1:从官网下载
# 访问 https://nodejs.org/
# 下载 LTS 版本并安装
# 方法2:使用 Chocolatey
choco install nodejs
# 方法3:使用 Scoop
scoop install nodejsmacOS 系统
bash
# 方法1:从官网下载
# 访问 https://nodejs.org/
# 方法2:使用 Homebrew
brew install node
# 方法3:使用 MacPorts
sudo port install nodejs18Linux 系统
bash
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# CentOS/RHEL/Fedora
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo dnf install -y nodejs
# Arch Linux
sudo pacman -S nodejs npm验证安装
bash
# 检查版本
node --version
npm --version
# 检查 npm 全局包位置
npm config get prefix
# 更新 npm 到最新版本
npm install -g npm@latest🚀 创建 React 项目
方法1:Create React App (推荐新手)
安装和创建项目:
bash
# 使用 npx(推荐)
npx create-react-app my-react-app
# 或者全局安装后使用
npm install -g create-react-app
create-react-app my-react-app
# 进入项目目录
cd my-react-app
# 启动开发服务器
npm start项目结构:
my-react-app/
├── public/
│ ├── index.html
│ ├── favicon.ico
│ └── manifest.json
├── src/
│ ├── App.js
│ ├── App.css
│ ├── index.js
│ ├── index.css
│ └── App.test.js
├── package.json
├── README.md
└── yarn.lock方法2:Vite (推荐生产项目)
创建项目:
bash
# 使用 npm
npm create vite@latest my-react-app -- --template react
# 使用 yarn
yarn create vite my-react-app --template react
# 使用 pnpm
pnpm create vite my-react-app --template react
# 进入项目并安装依赖
cd my-react-app
npm install
# 启动开发服务器
npm run devVite 项目结构:
my-react-app/
├── public/
│ └── vite.svg
├── src/
│ ├── App.jsx
│ ├── App.css
│ ├── main.jsx
│ ├── index.css
│ └── assets/
├── index.html
├── package.json
├── vite.config.js
└── README.md方法3:Next.js (全栈React框架)
创建项目:
bash
# 使用 create-next-app
npx create-next-app@latest 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 to use `src/` directory? No / Yes
Would you like to use App Router? No / Yes
Would you like to customize the default import alias? No / Yes
# 启动开发服务器
cd my-next-app
npm run dev方法4:手动搭建
创建基础结构:
bash
# 创建项目目录
mkdir my-react-manual
cd my-react-manual
# 初始化 package.json
npm init -y
# 安装 React 相关依赖
npm install react react-dom
# 安装开发依赖
npm install --save-dev @vitejs/plugin-react vite创建基础文件:
index.html:
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My React App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>src/main.jsx:
jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)src/App.jsx:
jsx
import { useState } from 'react'
function App() {
const [count, setCount] = useState(0)
return (
<div>
<h1>Hello React!</h1>
<button onClick={() => setCount(count + 1)}>
点击次数: {count}
</button>
</div>
)
}
export default Appvite.config.js:
javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})🔧 开发工具配置
VS Code 扩展推荐
必装扩展:
json
{
"recommendations": [
"bradlc.vscode-tailwindcss",
"esbenp.prettier-vscode",
"ms-vscode.vscode-typescript-next",
"formulahendry.auto-rename-tag",
"christian-kohler.path-intellisense",
"ms-vscode.vscode-json"
]
}React 相关扩展:
- ES7+ React/Redux/React-Native snippets:代码片段
- Bracket Pair Colorizer 2:括号配对着色
- Auto Rename Tag:自动重命名标签
- GitLens:Git 增强
- Thunder Client:API 测试
代码格式化配置
Prettier 配置 (.prettierrc):
json
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false
}ESLint 配置 (.eslintrc.js):
javascript
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['react', '@typescript-eslint'],
rules: {
'react/react-in-jsx-scope': 'off',
},
settings: {
react: {
version: 'detect',
},
},
};🌐 浏览器开发工具
React Developer Tools
安装浏览器扩展:
- Chrome: React Developer Tools
- Firefox: React Developer Tools
- Edge: 从 Chrome 网上应用店安装
功能特性:
jsx
// 在组件中添加 displayName 便于调试
function MyComponent() {
return <div>Hello</div>;
}
MyComponent.displayName = 'MyComponent';
// 使用 React DevTools Profiler
import { Profiler } from 'react';
function onRenderCallback(id, phase, actualDuration) {
console.log('组件渲染信息:', { id, phase, actualDuration });
}
function App() {
return (
<Profiler id="App" onRender={onRenderCallback}>
<MyComponent />
</Profiler>
);
}📦 包管理器对比
npm vs yarn vs pnpm
npm (默认):
bash
# 安装依赖
npm install
npm install package-name
npm install --save-dev package-name
# 运行脚本
npm run build
npm start
# 全局安装
npm install -g package-nameYarn:
bash
# 安装 Yarn
npm install -g yarn
# 使用 Yarn
yarn install
yarn add package-name
yarn add --dev package-name
# 运行脚本
yarn build
yarn startpnpm (推荐):
bash
# 安装 pnpm
npm install -g pnpm
# 使用 pnpm
pnpm install
pnpm add package-name
pnpm add -D package-name
# 运行脚本
pnpm run build
pnpm start性能对比:
| 特性 | npm | yarn | pnpm |
|---|---|---|---|
| 安装速度 | 慢 | 快 | 最快 |
| 磁盘空间 | 大 | 大 | 小 |
| 离线支持 | 部分 | 好 | 好 |
| 安全性 | 好 | 好 | 好 |
🛠️ 项目模板选择
Create React App 适用场景
优点:
- 零配置开始
- 社区支持好
- 适合学习
- 内置测试环境
缺点:
- 构建速度慢
- 包体积大
- 配置不够灵活
bash
# 适合以下场景
npx create-react-app my-app # 标准 React 应用
npx create-react-app my-app --template typescript # TypeScript 项目Vite 适用场景
优点:
- 启动速度极快
- 热更新快
- 构建速度快
- 配置灵活
缺点:
- 相对较新
- 插件生态系统较小
bash
# 多种模板选择
npm create vite@latest my-app -- --template react
npm create vite@latest my-app -- --template react-tsNext.js 适用场景
优点:
- 服务端渲染
- 静态网站生成
- API 路由
- 文件系统路由
使用场景:
- SEO 重要的网站
- 需要服务端渲染
- 全栈应用开发
bash
npx create-next-app@latest my-next-app🔍 常见问题解决
Node.js 版本管理
使用 nvm (推荐):
bash
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 使用 nvm
nvm install 18.17.0
nvm use 18.17.0
nvm alias default 18.17.0
# 查看已安装版本
nvm list网络问题解决
配置 npm 镜像:
bash
# 使用淘宝镜像
npm config set registry https://registry.npmmirror.com
# 恢复官方镜像
npm config set registry https://registry.npmjs.org
# 查看当前镜像
npm config get registry使用 cnpm:
bash
# 安装 cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com
# 使用 cnpm 代替 npm
cnpm install
cnpm install react权限问题解决
全局包权限问题:
bash
# 创建全局目录
mkdir ~/.npm-global
# 配置 npm
npm config set prefix '~/.npm-global'
# 添加到环境变量 (添加到 ~/.bashrc 或 ~/.zshrc)
export PATH=~/.npm-global/bin:$PATH🎯 验证安装
创建测试项目
bash
# 创建测试项目
npx create-react-app test-installation
cd test-installation
# 启动开发服务器
npm start检查关键功能
jsx
// 修改 src/App.js 测试热更新
import React, { useState } from 'react';
import './App.css';
function App() {
const [message, setMessage] = useState('React 安装成功!');
return (
<div className="App">
<header className="App-header">
<h1>{message}</h1>
<button onClick={() => setMessage('热更新工作正常!')}>
测试热更新
</button>
<p>React 版本: {React.version}</p>
</header>
</div>
);
}
export default App;性能检查
bash
# 检查构建
npm run build
# 检查包大小
npm install -g bundlephobia
bundlephobia analyze
# 运行测试
npm test📝 本章小结
通过本章学习,你应该掌握了:
关键要点
- ✅ Node.js 和 npm 的安装配置
- ✅ 多种 React 项目创建方式
- ✅ 开发工具和扩展配置
- ✅ 浏览器开发工具使用
- ✅ 包管理器选择和使用
- ✅ 常见问题的解决方法
最佳实践
- 使用 LTS 版本的 Node.js:稳定可靠
- 选择合适的项目模板:根据需求选择
- 配置代码格式化工具:保持代码一致性
- 安装必要的开发工具:提高开发效率
- 定期更新依赖:保持安全性和性能
下一步
- 学习项目结构和文件组织
- 了解开发服务器的工作原理
- 掌握构建和部署流程
继续学习:下一章 - React 快速上手