如何写react项目脚手架
创建React项目脚手架
使用官方工具create-react-app是最快捷的方式。确保已安装Node.js(>=14.0.0)和npm(>=5.6),运行以下命令生成基础项目结构:
npx create-react-app my-app
cd my-app
npm start
自定义脚手架配置
如需深度定制,可通过eject暴露配置或手动配置:
npm run eject # 注意此操作不可逆
或手动创建以下核心文件:
webpack.config.js:打包配置babel.config.js:语法转换配置.eslintrc:代码规范配置
添加常用工具库
基础技术栈推荐组合:
npm install axios react-router-dom @reduxjs/toolkit styled-components
TypeScript支持可通过以下命令添加:

npx create-react-app my-app --template typescript
目录结构优化
推荐模块化组织方式:
src/
├── components/ # 通用组件
├── pages/ # 页面级组件
├── store/ # 状态管理
├── utils/ # 工具函数
├── App.tsx
└── index.tsx
集成代码规范
添加ESLint和Prettier保证代码一致性:
npm install eslint prettier eslint-config-prettier --save-dev
配置文件示例(.eslintrc.json):

{
"extends": ["react-app", "prettier"],
"rules": {
"react-hooks/exhaustive-deps": "warn"
}
}
自动化测试配置
添加Jest和React Testing Library:
npm install @testing-library/react @testing-library/jest-dom --save-dev
测试文件应放在__tests__目录或使用.test.js后缀。
持续集成部署
GitHub Actions示例(.github/workflows/deploy.yml):
name: Deploy
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm ci
- run: npm run build
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build






