Skip to content

Commit

Permalink
perf: 优化细节
Browse files Browse the repository at this point in the history
  • Loading branch information
huangmingfu committed Dec 25, 2024
1 parent f3add61 commit 1e6e027
Show file tree
Hide file tree
Showing 16 changed files with 75 additions and 207 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# 这些变量在开发环境、生产环境和测试环境中都会生效。

# 项目标题
VITE_APP_TITLE = React-Ts-Template
VITE_APP_TITLE = React-Mobile-Template

# 端口号
VITE_APP_PORT = 5173
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ dist-ssr
*.sln
*.sw?

.cache
.stylelintcache
.eslintcache
3 changes: 0 additions & 3 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
# 设置最新的淘宝镜像,加快安装依赖速度
registry = https://registry.npmmirror.com

# 安装依赖时锁定版本号
save-exact = true
158 changes: 48 additions & 110 deletions README.en-US.md
Original file line number Diff line number Diff line change
@@ -1,128 +1,66 @@
GitHub Repository: [React-Ts-Template](https://github.com/huangmingfu/react-ts-template)
# React Mobile Template

In modern frontend development, we often need to quickly set up a React project. With the `create-react-app` scaffold no longer being maintained, **React-Ts-Template** was born to address this need! This is a project template built on the latest **React 19, TypeScript, and Vite 6**, designed to help you rapidly start your project and save considerable configuration time. The template integrates various development standards and popular plugins, ready to use out of the box, allowing you to focus on implementing business logic!
GitHub Project Link: [React-Mobile-Template](https://github.com/huangmingfu/react-mobile-template)

This is a **mobile project template** based on [React-Ts-Template](https://github.com/huangmingfu/react-ts-template), aimed at helping you quickly start mobile H5 projects and save a lot of repetitive configuration time. The template integrates various development specifications and popular plugins, ready to use out of the box, allowing you to focus on business logic implementation!

## Features

- **Route Lazy Loading**: Implemented route lazy loading to improve page switching performance and reduce initial loading time. (See `router`)
- **Route Guards**: Encapsulated flexible route guard management to ensure user access control and enhance application security. (See `router`)
- **Global State Management**: Provides Zustand global state management example code, simplifying cross-component state sharing and improving development efficiency. (See `store`)
- **Axios Request Encapsulation**: Encapsulated Axios to uniformly handle HTTP requests and responses, simplifying interaction with backend interfaces. (See `services`)
- **Utility Functions & Hooks**: Provides some convenient and practical utility functions and hooks. (See `utils`, `hooks`)
- **react-dev-inspector Integration**: Click on page elements to open corresponding code in IDE, facilitating code debugging and improving development efficiency. (See `vite.config.ts`)
- **Automatic Import Order Beautification**: Integrated prettier-plugin-sort-imports plugin to automatically beautify import order, enhancing code readability and maintainability.
- **Others**: Provides commands for convenient environment-based running and building; configured code splitting strategy; local reverse proxy for CORS; and detailed `nanny-level comments`, etc.

## Technology Stack Overview

### 🛠 Technology Stack Selection

- **React 19 & React-DOM**: Using the latest version of React for high frontend performance and smoother user experience.
- **React-Router**:Latest v7 version, supports lazy loading of routes, optimizes page transition performance.
- **SCSS Preprocessing**: Fully adopts the new version of SCSS, using `@use` instead of `@import` for stronger modularity.
- **ahooks**: Provides rich React Hooks similar to VueUse, further simplifying logic code.
- **zustand**: Lightweight state management library. After comparing Redux, Dva, React-Toolkit, MobX, and `useContext` combined with `useReducer`, we chose the simpler Zustand.
- **Immer**: Simplifies immutable data structure operations, especially convenient for handling deeply nested objects.
- **es-toolkit**: A modern JavaScript utility library that provides a range of powerful functions for everyday use, with a smaller size and better performance (similar to lodash-es).
- **Axios**: Encapsulated HTTP request library for easier backend interface integration.
- **classnames**: Dynamic class name management tool, particularly suitable for conditional style rendering.
- **Dayjs**: Lightweight date processing library, providing APIs similar to Moment.js but with smaller size and better performance.

### 🔧 Other Recommended Tools

- **Alova.js**: New generation request tool, convenient for request data management.
- **SWR**: Another choice for data request caching and synchronization management.
- **Route Guard**: Flexible route guard management to ensure user access control and enhance application security. (See `router`)
- **Global State Management**: Provides Zustand global state management example code to simplify cross-component state sharing and improve development efficiency. (See `store`)
- **Axios Request Encapsulation**: Encapsulates Axios to uniformly handle HTTP requests and responses, simplifying interaction with backend interfaces. (See `services`)
- **Utility Functions and Hooks**: Provides convenient utility functions and hooks. (See `utils`, `hooks`)
- **react-dev-inspector Integration**: Click page elements to open corresponding code directly in IDE, facilitating developer debugging and improving development efficiency. (See `vite.config.ts`)
- **Automatic Import Sorting**: Integrated with prettier-plugin-sort-imports to automatically beautify import order, improving code readability and maintainability
- **Other Features**: Provides convenient commands for environment-specific running and packaging; configured code splitting strategy; local reverse proxy to solve cross-origin issues; detailed "nanny-level comments", etc.

## Technology Stack

### 🛠 Technology Selection

- **React 18 & React-DOM**: Using the latest React version for high-performance front-end and smoother user experience
- **React-Router**: Latest v7 version, supporting route lazy loading and optimizing page switching performance
- **rem**: Using rem units for mobile adaptation, ensuring consistent display across different devices
- **antd-mobile**: Alibaba's open-source mobile component library, providing rich UI components and simplifying development process
- **SCSS Preprocessor**: Fully adopting new SCSS version, using `@use` instead of `@import` for stronger modularity
- **ahooks**: Provides rich React Hooks similar to VueUse, further simplifying logical code
- **zustand**: Lightweight state management library
- **Immer**: Simplifies immutable data structure operations
- **es-toolkit**: Modern JavaScript utility library
- **Axios**: HTTP request library
- **classnames**: Dynamic class name management tool
- **Dayjs**: Lightweight date processing library

## Project Standards and Configuration

To ensure code consistency and standardization in team collaboration, **React-Ts-Template** introduces a complete set of project standards:
To ensure code consistency and standardization during team collaboration, the project introduces:

- **Full ESM Standard Usage**: Adopts modular imports, aligning with modern JavaScript development trends.
- **Mandatory pnpm Package Manager**: Improves dependency installation speed, reduces disk space usage, and solves phantom dependency issues.
- **BEM Style Naming Convention**: Clear structure, reduces style conflicts, improves code maintainability (CSS Modules wasn't adopted for easier style penetration, but you can use xxx.module.scss if needed).
- **File and Folder Naming**: Uniformly uses `kebab-case`, which is most reliable, especially when sharing code through version control across different operating systems with varying case sensitivity.
- **Full ESM Standard**: Using modular imports
- **Package Manager**: Strictly using pnpm
- **Style Naming Convention**: BEM naming standard
- **File Naming**: Unified `kebab-case`

### 💡 Efficient Code Standard Management

Besides code structure standardization, the project integrates various code quality inspection tools to ensure development experience and code quality:

- **ESLint**: Code style and error checking, upgraded to the latest version, deprecated `.eslintignore` in favor of `ignores` configuration.
- **Prettier**: Unified code formatting to avoid conflicts due to formatting issues in team collaboration.
- **Stylelint**: Style-specific lint tool ensuring SCSS code consistency.
- **Commitlint** + **Husky** + **Lint-Staged**: Works with Git Hooks to standardize code submissions and prevent low-quality code from entering the repository.
- **EditorConfig**: Unified editor configuration to reduce issues caused by editor differences.

## Project Structure

```tree
├── .vscode # VSCode editor configuration folder
│ └── settings.json # Specific VSCode editor settings
│ └── extensions.json # VSCode recommended plugins
├── .husky # Husky configuration folder for managing Git hooks
│ └── commit-msg # Commit message check hook configuration
│ └── pre-commit # Formatting hook configuration
├── .github # GitHub specific configuration and workflow folder
│ └── workflows # GitHub Actions workflow configuration
│ └── deploy.yml # Continuous integration configuration file
├── public # Static resource directory for assets not processed by Vite
├── src # Source code directory
│ ├── assets # Static assets like images, fonts, etc.
│ ├── components # Common components directory
│ │ ├── high-light # Code highlighting component
│ │ └── auto-scroll-to-top # Auto scroll to top component
│ │ └── ...
│ ├── hooks # Custom React Hooks
│ │ └── use-design # Design-related custom Hook
│ │ └── ...
│ ├── layouts # Page layout components
│ ├── views # Page components
│ ├── router # Route configuration
│ │ └── utils # Route-related utility functions
│ │ └── ...
│ ├── services # API service encapsulation
│ ├── store # State management
│ │ └── modules # State management modules
│ │ │ └── use-loading-store.ts # Counter loading state management
│ │ └── ...
│ ├── styles # Styles
│ ├── types # TypeScript type definitions
│ └── utils # Utility functions
├── .env # Environment configuration file
├── .editorconfig # Editor configuration file for unified code style across editors
├── eslint.config.js # ESLint configuration file for code style and error checking
├── .prettierrc.js # Prettier configuration file for code formatting
├── stylelint.config.js # Stylelint configuration file for style file standards
├── .commitlintrc.js # Commitlint configuration file for Git commit message style checking
├── lint-staged.config.js # Lint-Staged configuration file for running Linters before Git commits
├── package.json # Project dependency configuration file
├── tsconfig.json # TypeScript configuration file
└── vite.config.ts # Vite configuration file for build and service options
```

## Others

### 📦 About Route Caching (keep-alive)

> React officially hasn't implemented functionality similar to Vue's \<keep-alive\>. React team rejected adding this feature based on two considerations, which you can search and read about. To achieve state preservation, the official team recommends these two manual state preservation methods:
- Lift the state of components needing state preservation to their parent components.
- Use CSS visible property to control the rendering of components needing state preservation, instead of using if/else, to prevent React from unmounting them.

> However, there are some libraries that implement this functionality, such as react-router-cache-route, react-activation, keepalive-for-react, etc. If your project needs to handle a small amount of state caching data, it's better to follow React's official recommendations and solve state caching issues manually.
---
- **ESLint**: Code style and error checking
- **Prettier**: Unified code formatting
- **Stylelint**: Style linting tool
- **Commitlint + Husky + Lint-Staged**: Git Hooks for code commit standardization
- **EditorConfig**: Unified editor configuration

## Summary

The **React-Ts-Template** project template aims to reduce developers' tedious configuration steps during project initialization through preset best practice configurations, allowing you to get started with project development faster. Meanwhile, it's equipped with mature development toolchains and powerful plugin support to ensure team development consistency and code quality. If you're looking for an efficient React project template, why not try **React-Ts-Template**!
**React-Mobile-Template** aims to reduce initial configuration steps through preset best practices, allowing developers to quickly start project development. It comes with a mature development toolchain and powerful plugin support to ensure team development consistency and high-quality code.

**👉 Star the project and start your React mobile project journey!**

> [React-Mobile-Template](https://github.com/huangmingfu/react-mobile-template)
**👉 Star the project now and start your React project journey!**
## Notes

> [React-Ts-Template](https://github.com/huangmingfu/react-ts-template)
1. Currently, some UI libraries do not support React 19. This project uses version 18.3.1, so be cautious when upgrading the React version.
2. The `postcss-pxtorem` plugin does not support inline styles, so a `px2rem` function is provided in `utils` to address this. Example: `<div style={{ width: px2rem(100) }}>test</div>`
3. The `postcss-pxtorem` plugin will not convert px to rem in the following scenarios:

## Note
> 1.Currently, some UI libraries do not support React 19. Please be cautious when installing and using them.
> 2.This project does not use any features specific to version 19. If needed, you can directly downgrade to version 18 using the following command.
```bash
pnpm install [email protected] [email protected]
```
(1). When styles are imported in `main.ts`, such as `import '@/styles/scss/global.scss';`. It is recommended to import styles that do not involve px, such as `reset.css`.
19 changes: 7 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ GitHub 项目地址:[React-Mobile-Template](https://github.com/huangmingfu/rea

### 🛠 技术栈选型

- **React 19 & React-DOM**:使用最新版 React 实现前端高性能和更流畅的用户体验。
- **React 18 & React-DOM**:使用最新版 React 实现前端高性能和更流畅的用户体验。
- **React-Router**:最新v7版本,支持路由懒加载,优化页面切换性能。
- **rem**:使用 rem 单位进行移动端适配,确保在不同设备上有一致的显示效果(本项目也配置了vw参考可供开发者自行选择使用)。
- **antd-mobile**:阿里巴巴开源的移动端组件库,提供丰富的 UI 组件,简化开发流程。
Expand Down Expand Up @@ -71,20 +71,15 @@ GitHub 项目地址:[React-Mobile-Template](https://github.com/huangmingfu/rea

## 总结

**React-Mobile-Template** 项目模板的目标是通过预设的最佳实践配置,减少开发者在项目初始化时的琐碎配置步骤,让你可以更快上手项目开发。同时,配备了成熟的开发工具链和强大的插件支持,以确保团队开发的一致性和代码的高质量。如果你正在寻找一款高效的 React 项目模板,不妨试试 **React-Mobile-Template**
**React-Mobile-Template** 项目模板的目标是通过预设的最佳实践配置,减少开发者在项目初始化时的琐碎配置步骤,让你可以更快上手项目开发。同时,配备了成熟的开发工具链和强大的插件支持,以确保团队开发的一致性和代码的高质量。如果你正在寻找一款高效的 `React 移动端项目模板`,不妨试试 **React-Mobile-Template**

**👉 赶快 Star 项目,开启你的 React 项目之旅**
**👉 赶快 Star 项目,开启你的 React 移动端项目之旅**

> [React-Mobile-Template](https://github.com/huangmingfu/react-mobile-template)
## 注意

> 1.目前有一些ui库还未支持React19,本项目使用的是18.3.1版本,谨慎升级react版本。
> 2.postcss-pxtorem插件不支持内联样式,所以 `utils` 里面配备了 `px2rem` 函数。示例:
```ts
<div style={{ width: px2rem(100) }}>test</div>
```

> 3. 以下场景pxtorem插件不会转换rem:
> (1) 在main.ts里引入样式,如 `import '@/styles/scss/global.scss';`,建议引入不涉及px的样式,如reset.css。
1.目前有一些ui库还未支持React19,本项目使用的是18.3.1版本,谨慎升级react版本。
2.postcss-pxtorem插件不支持内联样式,所以 `utils` 里面配备了 `px2rem` 函数解决。示例:`<div style={{ width: px2rem(100) }}>test</div>`
3. 以下场景pxtorem插件不会转换rem:
(1).在main.ts里引入样式,如 `import '@/styles/scss/global.scss';`,建议引入不涉及px的样式,如reset.css。
2 changes: 1 addition & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import tseslint from 'typescript-eslint';
export default tseslint.config(
{ ignores: ['dist', 'dist*', 'node_modules'] },
{
settings: { react: { version: '19.0' } },
settings: { react: { version: '18.3' } },
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
Expand Down
6 changes: 3 additions & 3 deletions lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @type {import('lint-staged').Config} */
export default {
'*.{ts,tsx,js,jsx,cjs,mjs}': 'eslint --fix',
'*.{css,scss,less}': 'stylelint --fix',
'*.{ts,tsx,js,jsx,cjs,mjs,html,css,scss,less,json}': 'prettier --write',
'*.{ts,tsx,js,jsx,cjs,mjs}': 'eslint --fix --cache',
'*.{css,scss,less}': 'stylelint --fix --cache',
'*.{ts,tsx,js,jsx,cjs,mjs,html,css,scss,less,json}': 'prettier --write --cache',
};
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,9 @@
"preview:pro": "pnpm vite preview -m pro",
"ts:check": "tsc --noEmit",
"lint:eslint": "eslint --max-warnings 0 \"**/*.{ts,tsx,js,jsx,cjs,mjs}\" --fix --cache",
"lint:format": "prettier --write \"**/*.{ts,tsx,js,jsx,cjs,mjs,html,scss,css,less,json}\"",
"lint:format": "prettier --write --cache \"**/*.{ts,tsx,js,jsx,cjs,mjs,html,scss,css,less,json}\"",
"lint:style": "stylelint \"**/*.{css,scss,less}\" --fix --cache",
"lint:all": "pnpm run lint:eslint && pnpm run lint:style && pnpm run lint:format",
"lint:lint-staged": "lint-staged",
"prepare": "husky install",
"preinstall": "npx only-allow pnpm",
"clean": "rm -rf node_modules dist dist-*",
Expand All @@ -51,8 +50,8 @@
"dayjs": "^1.11.13",
"es-toolkit": "^1.30.1",
"immer": "^10.1.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react": "~18.3.1",
"react-dom": "~18.3.1",
"react-router": "^7.1.1",
"zustand": "^5.0.2"
},
Expand Down
4 changes: 2 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 1e6e027

Please sign in to comment.