目录
简洁版:
新建文件夹->创建项目,下载依赖->上传文件夹到代码托管平台
npm create vite@latest my-react-ts-app -- --template react-ts # 使用vite创建一个react+ts的项目
cd my-react-ts-app # 进入项目目录
npm install # 安装依赖
npm run dev # 启动开发服务器
下载依赖:路由React Router、代码规范eslint+Prettier、tailwind css、 全局状态管理Zustand
按需引入,跟着我的目录来吧。
碎碎念版:
一、前置背景
前提背景,我目前没有系统地学习过 react,只学习过 react 文档的前几页,大概知道一些原理,有过 react native 项目经验(机缘巧合哈哈),打算在搭建的过程中边学边做,于是查了一些资料,感觉和 vue 的项目差不多,所以自己手动搭建,以此记录。希望看到这篇文章的人能通过这个 理解到这个项目的搭建过程有一个了解,大部分人可以无脑粘贴复制,都是经过检验的!
需要资源:
一台电脑——我的是 macOS 环境
node——目前我是选择 node v20.18.3
npm/pnpm——npm 10.8.2
一些计算机知识——比如有过 vue 的项目搭建经验,大致流程差不多
目标:
1.达到启动
2.引入: ts、react-dom、路由、样式库、axios、vite、状态管理的库、代码管理的库 eslint 或者prettier等等,其他需要的再后面加。
3.搭建的项目不要求多么完善,只要求干净基础,后续扩展起来比较方便。
二、正式开始
我设想的主要步骤:新建文件夹->创建项目,下载依赖->上传文件夹到代码托管平台
工作量应该在第二步。
第一步:
新建文件夹,比如我这里就建了一个文件夹,然后我用编辑器打开项目,打开终端,接下来就开始在这里执行我后续的操作:
第二步:
2.1 Vite 一分钟创建项目
如何创建一个新的项目?可以去看文档:创建一个 React 新项目 | React 中文文档 | React 中文网
这里推荐了几种方式,Create React App这种方式,或者其他工具链去创建,我因为之前用过 vite,比较简单快速上手,支持 ts,所以我这里使用 vite 去创建。两者的区别我理解就是打包构建的工具不一样,前者是使用 webpack。
于是从官网点击 vite的官网:https://vite.dev/guide/
可以从这里查看构建后的项目结构:Vitejs - Vite (forked) - StackBlitz
兼容性说明
Vite 需要Node.js版本 18+ 或 20+。但是,某些模板需要更高的 Node.js 版本才能运行,如果您的包管理器对此发出警告,请升级。
使用官方推荐去搭建很简单,这里提到支持react-ts
那么在终端中运行以下命令,我要创建的项目名称是:my-react-ts-app
npm create vite@latest my-react-ts-app -- --template react-ts
于是两秒后,项目创建好了:
然后下载、启动:
cd my-react-ts-app # 进入项目目录
npm install # 安装依赖
npm run dev # 启动开发服务器
如下:
这样就完成了一个基本的 React 项目的搭建,使用 vite 真快!一分钟!接下来根据需要添加其他库、组件和功能来丰富应用程序。
2.2 引入相关依赖
顺序:代码规范selint+prettier、路由
react-router-dom
(v6)、状态管理Redux、Tailwind CSS、axios等等
基本项目结构:
my-react-app/
├── src/ # 源代码目录
│ ├── assets/ # 静态资源
│ ├── components/ # 公共组件
│ │ └── Counter.tsx # 计数器组件
│ ├── compoents/ # 组件目录(可能是拼写错误)
│ ├── hooks/ # 自定义 hooks
│ ├── pages/ # 页面组件
│ │ ├── Home.tsx # 首页
│ │ └── About.tsx # 关于页面
│ ├── router/ # 路由配置
│ │ └── index.tsx # 路由定义
│ ├── store/ # Redux 状态管理
│ │ ├── features/ # Redux slices
│ │ │ └── counterSlice.ts
│ │ ├── hooks.ts # Redux hooks
│ │ └── index.ts # store 配置
│ ├── utils/ # 工具函数
│ ├── App.tsx # 根组件
│ ├── App.css # 根组件样式
│ ├── main.tsx # 入口文件
│ └── index.css # 全局样式(包含 Tailwind)
├── public/ # 公共资源
├── node_modules/ # 依赖包
├── package.json # 项目配置
├── package-lock.json # 依赖锁定文件
├── postcss.config.js # PostCSS 配置
├── tailwind.config.js # Tailwind 配置
├── tsconfig.json # TypeScript 配置
├── tsconfig.node.json # Node TypeScript 配置
├── tsconfig.app.json # 应用 TypeScript 配置
├── vite.config.ts # Vite 配置
├── .eslintrc.js # ESLint 配置
├── .prettierrc # Prettier 配置
├── .prettierignore # Prettier 忽略文件
├── .eslintignore # ESLint 忽略文件
├── .vscode/ # VS Code 配置
└── index.html # HTML 模板
2.2.1 代码规范
引入代码规范我认为是必须的,常见的是 ESLint(代码质量) + Prettier(格式化)。
npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-react eslint-plugin-react-hooks
创建文件:
.eslintrc.js
module.exports = {
settings: {
react: {
version: "detect"
}
},
root: true,
env: {
browser: true,
node: true,
es6: true
},
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2021,
sourceType: "module",
ecmaFeatures: {
jsx: true
}
},
plugins: ["react", "@typescript-eslint", "react-hooks", "prettier"],
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"prettier",
"plugin:prettier/recommended"
],
rules: {
"no-var": "error",
"no-multiple-empty-lines": ["error", { max: 1 }],
"no-use-before-define": "off",
"prefer-const": "off",
"no-irregular-whitespace": "off",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/ban-ts-ignore": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"react/prop-types": "off",
"react/react-in-jsx-scope": "off",
"react/jsx-uses-react": "off",
"react/jsx-uses-vars": "error",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"prettier/prettier": "warn",
}
};
.prettierrc
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2,
"bracketSpacing": true,
"arrowParens": "always"
}
.eslintignore .prettierignore 内容如下:
node_modules
dist
配置 lint的启动代码:
"lint": "eslint 'src/**/*.{js,ts,tsx}'",
"format": "prettier --write 'src/**/*.{js,ts,tsx}'",
2.2.2 路由
使用react-router-dom
(v6),并且确保TypeScript 的类型支持教程到处都有,就不推荐了
npm install react-router-dom @types/react-router-dom
引用路由:
新建三个页面:Home. About NotFound
src/pages/Home.tsx
import React from 'react';
const Home: React.FC = () => {
return (
<div style={{ color: 'blue' }}>
<h1>首页</h1>
<p>欢迎来到我们的应用</p>
</div>
);
};
export default Home;
配置路由:
src/router/index.tsx
import { createBrowserRouter } from 'react-router-dom';
import Home from '../pages/Home';
import About from '../pages/About';
import App from '../App';
const router = createBrowserRouter([
{
path: '/',
element: <App />,
children: [
{
index: true,
element: <Home />,
},
{
path: 'about',
element: <About />,
},
{
path: 'dashboard',
element: <div>仪表盘页面</div>,
},
{
path: 'users',
element: <div>用户管理页面</div>,
},
],
},
]);
export default router;
使用,App.tsx
// import { useState } from 'react'
// import reactLogo from './assets/react.svg'
// import viteLogo from '/vite.svg'
import './App.css'
import { Link, Outlet } from 'react-router-dom'
function App() {
// const [count, setCount] = useState(0)
return (
<div className="app-container">
{/* 侧边栏 */}
<aside className="sidebar">
<div className="logo">
<h2>管理系统</h2>
</div>
<nav className="sidebar-nav">
<ul>
<li>
<Link to="/">
<i className="icon">🏠</i>
<span>首页</span>
</Link>
</li>
<li>
<Link to="/about">
<i className="icon">ℹ️</i>
<span>关于我们</span>
</Link>
</li>
</ul>
</nav>
</aside>
{/* 主要内容区域 */}
<div className="main-content">
{/* 顶部导航栏 */}
<header className="top-nav">
</header>
{/* 主内容区域 */}
<main className="content">
<Outlet />
</main>
</div>
</div>
)
}
export default App
生成界面如下:这是基础配置,之后可以根据这个进行扩展。
2.2.3 状态管理
使用Zustand,本来想使用Redux Toolkit: 概览 | Redux 中文官网
详细文档:Redux Toolkit | Redux Toolkit如果是企业级开发的话,状态管理应该是会比较复杂的,但是这个是在太复杂了,我们好像用不了那么多,于是换了轻量级的Zustand。优点很多:
- 简单易用:不需要 Provider 包裹
- 类型安全:完整的 TypeScript 支持
- 状态持久化:使用 persist 中间件
- 开发工具支持:使用 devtools 中间件
- 性能优化:按需更新,避免不必要的重渲染
而且现在我们其他项目也用的Zustand。
引入
npm install zustand
教程太多了,暂时不写了。这个学习起来也很快,看文档吧。
流程就是:创建 Store 文件、使用中间件(devtools 和 persist)、导入 store、使用 useStore hook 获取状态和方法、引入组件。
2.2.4 css样式管理
使用tailwindcss
安装 Tailwind CSS 及其依赖工具(PostCSS 和 Autoprefixer)
官网:推荐 tailwindcss v4版本了,根据需要引入使用 Vite 安装 Tailwind CSS - Tailwind CSS
引入:
npm install -D tailwindcss postcss autoprefixer
配置tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
配置 PostCSS(可选)
postcss.config.js 用于通过插件来转换 CSS。启用 Tailwind CSS 插件和 Autoprefixer 插件,压缩 CSS 文件等等
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
引入 Tailwind CSS
在 src/index.css
文件中添加以下代码:
@tailwind base;
@tailwind components;
@tailwind utilities;
使用:
<p className="text-lg text-red-500 mb-8">欢迎来到我们的应用</p>
如果字体变成红色,那么就代表生效了。
第三步:
上传到代码仓库,因为我们已经有文件夹,所有在文件夹下的终端里执行如下:
git init
git remote add origin https://你的仓库地址
git add.
git commit -m "你的信息“
git push -u origin master
最后做一些收尾工作,比如完善一下项目的.gitignore. README等。
因为担心会因为版本问题和团队开发的时候出现差异,所以我都使用了固定版本,定期进行升级,react使用的是 18.2.0。