React Installation
Overview
This chapter will detail how to set up a React development environment, including Node.js installation, development tool configuration, creating your first React project, and more. We will learn multiple ways to create React projects, as well as necessary development tool installations.
🛠️ Prerequisites
Required Software
Node.js and npm
# Check if Node.js is installed
node --version
# Should display: v18.0.0 or higher
# Check npm version
npm --version
# Should display: 8.0.0 or higherRecommended Configuration:
- Node.js 18.0+ or 20.0+ (LTS version)
- npm 8.0+ or yarn 1.22+
- Modern browsers (Chrome, Firefox, Safari, Edge)
Optional Tools
- Git: Version control
- VS Code: Recommended code editor
- Chrome DevTools: Debugging tools
📥 Node.js Installation
Windows Systems
# Method 1: Download from official website
# Visit https://nodejs.org/
# Download LTS version and install
# Method 2: Use Chocolatey
choco install nodejs
# Method 3: Use Scoop
scoop install nodejsmacOS Systems
# Method 1: Download from official website
# Visit https://nodejs.org/
# Method 2: Use Homebrew
brew install node
# Method 3: Use MacPorts
sudo port install nodejs18Linux Systems
# 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 npmVerifying Installation
# Check versions
node --version
npm --version
# Check npm global package location
npm config get prefix
# Update npm to latest version
npm install -g npm@latest🚀 Creating React Projects
Method 1: Create React App (Recommended for Beginners)
Installation and project creation:
# Using npx (recommended)
npx create-react-app my-react-app
# Or install globally first then use
npm install -g create-react-app
create-react-app my-react-app
# Enter project directory
cd my-react-app
# Start development server
npm startProject Structure:
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.lockMethod 2: Vite (Recommended for Production Projects)
Creating a project:
# Using npm
npm create vite@latest my-react-app -- --template react
# Using yarn
yarn create vite my-react-app --template react
# Using pnpm
pnpm create vite my-react-app --template react
# Enter and install dependencies
cd my-react-app
npm install
# Start development server
npm run devVite Project Structure:
my-react-app/
├── public/
│ └── vite.svg
├── src/
│ ├── App.jsx
│ ├── App.css
│ ├── main.jsx
│ ├── index.css
│ └── assets/
├── index.html
├── package.json
├── vite.config.js
└── README.mdMethod 3: Next.js (Full-stack React Framework)
Creating a project:
# Using create-next-app
npx create-next-app@latest my-next-app
# Select configuration options
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
# Start development server
cd my-next-app
npm run devMethod 4: Manual Setup
Creating basic structure:
# Create project directory
mkdir my-react-manual
cd my-react-manual
# Initialize package.json
npm init -y
# Install React dependencies
npm install react react-dom
# Install dev dependencies
npm install --save-dev @vitejs/plugin-react viteCreating basic files:
index.html:
<!DOCTYPE html>
<html lang="en">
<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:
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:
import { useState } from 'react'
function App() {
const [count, setCount] = useState(0)
return (
<div>
<h1>Hello React!</h1>
<button onClick={() => setCount(count + 1)}>
Click count: {count}
</button>
</div>
)
}
export default Appvite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})🔧 Development Tool Configuration
VS Code Extensions Recommendations
Required Extensions:
{
"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-related Extensions:
- ES7+ React/Redux/React-Native snippets: Code snippets
- Bracket Pair Colorizer 2: Bracket pairing colorization
- Auto Rename Tag: Auto rename tags
- GitLens: Git enhancement
- Thunder Client: API testing
Code Formatting Configuration
Prettier Configuration (.prettierrc):
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false
}ESLint Configuration (.eslintrc.js):
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',
},
},
};🌐 Browser Development Tools
React Developer Tools
Installing browser extensions:
- Chrome: React Developer Tools
- Firefox: React Developer Tools
- Edge: Install from Chrome Web Store
Features:
// Add displayName to components for easier debugging
function MyComponent() {
return <div>Hello</div>;
}
MyComponent.displayName = 'MyComponent';
// Using React DevTools Profiler
import { Profiler } from 'react';
function onRenderCallback(id, phase, actualDuration) {
console.log('Component render info:', { id, phase, actualDuration });
}
function App() {
return (
<Profiler id="App" onRender={onRenderCallback}>
<MyComponent />
</Profiler>
);
}📦 Package Manager Comparison
npm vs yarn vs pnpm
npm (Default):
# Install dependencies
npm install
npm install package-name
npm install --save-dev package-name
# Run scripts
npm run build
npm start
# Global install
npm install -g package-nameYarn:
# Install Yarn
npm install -g yarn
# Using Yarn
yarn install
yarn add package-name
yarn add --dev package-name
# Run scripts
yarn build
yarn startpnpm (Recommended):
# Install pnpm
npm install -g pnpm
# Using pnpm
pnpm install
pnpm add package-name
pnpm add -D package-name
# Run scripts
pnpm run build
pnpm startPerformance Comparison:
| Feature | npm | yarn | pnpm |
|---|---|---|---|
| Install Speed | Slow | Fast | Fastest |
| Disk Space | Large | Large | Small |
| Offline Support | Partial | Good | Good |
| Security | Good | Good | Good |
🛠️ Project Template Selection
Create React App Use Cases
Advantages:
- Zero configuration to start
- Good community support
- Good for learning
- Built-in testing environment
Disadvantages:
- Slow build speed
- Large bundle size
- Less flexible configuration
# Suitable for the following scenarios
npx create-react-app my-app # Standard React app
npx create-react-app my-app --template typescript # TypeScript projectVite Use Cases
Advantages:
- Extremely fast startup
- Fast hot reload
- Fast build speed
- Flexible configuration
Disadvantages:
- Relatively new
- Smaller plugin ecosystem
# Multiple template options
npm create vite@latest my-app -- --template react
npm create vite@latest my-app -- --template react-tsNext.js Use Cases
Advantages:
- Server-side rendering
- Static site generation
- API routes
- File system routing
Use Cases:
- SEO-important websites
- Need server-side rendering
- Full-stack application development
npx create-next-app@latest my-next-app🔍 Common Problem Solutions
Node.js Version Management
Using nvm (Recommended):
# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# Using nvm
nvm install 18.17.0
nvm use 18.17.0
nvm alias default 18.17.0
# View installed versions
nvm listNetwork Problem Solutions
Configuring npm registry:
# Use Taobao mirror
npm config set registry https://registry.npmmirror.com
# Restore official registry
npm config set registry https://registry.npmjs.org
# View current registry
npm config get registryUsing cnpm:
# Install cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com
# Use cnpm instead of npm
cnpm install
cnpm install reactPermission Problem Solutions
Global package permission issues:
# Create global directory
mkdir ~/.npm-global
# Configure npm
npm config set prefix '~/.npm-global'
# Add to environment variable (add to ~/.bashrc or ~/.zshrc)
export PATH=~/.npm-global/bin:$PATH🎯 Verifying Installation
Creating a Test Project
# Create test project
npx create-react-app test-installation
cd test-installation
# Start development server
npm startChecking Key Features
// Modify src/App.js to test hot reload
import React, { useState } from 'react';
import './App.css';
function App() {
const [message, setMessage] = useState('React installation successful!');
return (
<div className="App">
<header className="App-header">
<h1>{message}</h1>
<button onClick={() => setMessage('Hot reload is working!')}>
Test Hot Reload
</button>
<p>React version: {React.version}</p>
</header>
</div>
);
}
export default App;Performance Check
# Check build
npm run build
# Check bundle size
npm install -g bundlephobia
bundlephobia analyze
# Run tests
npm test📝 Chapter Summary
Through this chapter, you should have mastered:
Key Takeaways
- ✅ Node.js and npm installation and configuration
- ✅ Multiple React project creation methods
- ✅ Development tools and extension configuration
- ✅ Browser development tools usage
- ✅ Package manager selection and usage
- ✅ Common problem solutions
Best Practices
- Use LTS version of Node.js: Stable and reliable
- Choose appropriate project template: Based on requirements
- Configure code formatting tools: Maintain code consistency
- Install necessary development tools: Improve development efficiency
- Regularly update dependencies: Maintain security and performance
Next Steps
- Learn project structure and file organization
- Understand how development server works
- Master build and deployment process
Continue Learning: Next Chapter - React Quick Start