React项目搭建教程

React项目搭建教程

1. 准备开发环境

1.1 安装Node.js和npm

在开始React项目开发之前,你需要安装Node.js和npm(Node Package Manager)。

  • 推荐访问Node.js官网下载长期支持版(LTS)

  • 安装过程中,会自动安装npm

  • 可以通过以下命令验证安装:

    bash 复制代码
    node --version
    npm --version

1.2 全局安装Create React App

bash 复制代码
npm install -g create-react-app

2. 创建React项目

2.1 使用Create React App初始化项目

bash 复制代码
npx create-react-app my-react-app
cd my-react-app

2.2 项目目录结构说明

复制代码
my-react-app/
├── README.md
├── node_modules/
├── package.json
├── .gitignore
├── public/
│   ├── index.html
│   └── favicon.ico
└── src/
    ├── App.js
    ├── App.css
    ├── index.js
    └── index.css

3. 项目配置

3.1 package.json脚本

json 复制代码
{
  "scripts": {
    "start": "react-scripts start",     // 启动开发服务器
    "build": "react-scripts build",      // 生产打包
    "test": "react-scripts test",        // 运行测试
    "eject": "react-scripts eject"       // 弹出配置(谨慎使用)
  }
}

3.2 添加常用依赖

bash 复制代码
# 状态管理
npm install redux react-redux

# 路由
npm install react-router-dom

# 网络请求
npm install axios

# UI组件库(可选)
npm install antd

4. 开发和运行

4.1 启动开发服务器

bash 复制代码
npm start

自动打开 http://localhost:3000,支持热重载

4.2 生产构建

bash 复制代码
npm run build

生成优化的生产文件在 build/ 目录

5. 推荐的项目结构

复制代码
src/
├── components/       // 通用组件
├── pages/            // 页面组件
├── redux/            // 状态管理
│   ├── actions/
│   ├── reducers/
│   └── store.js
├── services/         // 网络请求
├── utils/            // 工具函数
├── App.js
└── index.js

6. 代码规范

6.1 推荐安装ESLint和Prettier

bash 复制代码
npm install eslint prettier -D

6.2 .eslintrc 配置示例

json 复制代码
{
  "extends": [
    "react-app",
    "react-app/jest"
  ],
  "rules": {
    "no-console": "warn",
    "react/prop-types": "error"
  }
}

7. 常见问题与解决方案

  1. 模块导入问题:使用绝对路径

    json 复制代码
    // jsconfig.json
    {
      "compilerOptions": {
        "baseUrl": "src"
      }
    }
  2. 跨域请求:配置代理

    json 复制代码
    // package.json
    {
      "proxy": "https://api.example.com"
    }

8. 持续集成与部署

  • 可选平台:Netlify、Vercel、GitHub Pages
  • 配置CI/CD pipeline
相关推荐
YFF菲菲兔15 小时前
调度系统和调和系统的桥梁
react.js
YFF菲菲兔19 小时前
commitRoot 源码解析
react.js
星栈2 天前
Dioxus 的响应式系统:`Signal`、`Memo`、`Effect` 和异步状态到底该怎么分工
前端·前端框架
光影少年2 天前
react批量更新、同步/异步更新场景
前端·react.js·掘金·金石计划
YFF菲菲兔2 天前
completeRoot 源码解析
react.js
光影少年3 天前
React 合成事件机制、和原生事件区别、事件冒泡阻止
前端·react.js·掘金·金石计划
禅思院3 天前
路由性能优化终极指南:从懒加载漏洞到边缘渲染的架构跃迁
前端·架构·前端框架
怕浪猫3 天前
Electron 系列文章封面图
算法·架构·前端框架
星栈3 天前
Dioxus 的 `rsx!` 语法:如果你会 React,上手确实特别快
前端·前端框架
YFF菲菲兔3 天前
finishConcurrentRender 源码解析
react.js