我如何构建我的 React 项目

2025-06-07

我如何构建我的 React 项目

有没有想过,React 应用可以对 bug 嗤之以鼻,还能轻松应对意大利面条式代码?让我们踏上旅程,打造一个强大的 React 应用,让它能够经受住糟糕编码习惯的考验。

在那些新手的日子里,我的代码就像一头野兽——功能齐全,却又极其混乱。项目结构(如果可以这么称呼的话)简直是一团乱麻。这对于我最初的项目来说还算可以,但随着项目的发展,复杂性也随之增加,混乱随之而来。

缺乏经验的开发者⤵
图片描述

经验丰富的开发者⤵

图片描述

随着项目的每次扩展,查找特定的代码片段就像大海捞针一样困难,最终才发现这根针是代码深处某个地方的变量,名字很贴切,叫做“针”。

在你的代码库变成一本无法解开的神秘小说之前,花点时间学习如何构建你的 React 项目。

项目应该是这样的:

src
|
+-- assets            
|
+-- components        
|
+-- config           
|
+-- features          
|
+-- hooks             
|
+-- lib               
|
+-- providers         
|
+-- routes            
|
+-- stores            
|
+-- test              
|
+-- types             
|
+-- utils            
Enter fullscreen mode Exit fullscreen mode

components:为整个王国增光添彩的共享组件
config:全局配置、环境变量和secrets
features:基于功能的模块的库
hooks:神秘的钩子,在整个领域共享
libs:重新导出为应用程序预先配置的不同库
providers:应用程序生命力的守护者,提供者
routes:路线配置
stores:全局状态存储
test:试验的舞台,实用程序和模拟服务器证明它们的勇气
types:整个应用程序使用的基本类型
utils:共享实用程序功能


现在,让我们深入了解一下该功能的核心。

src/features/my-new-feature
|
+-- api         # Declarations and API hooks, a symphony of requests for this feature
|
+-- assets      # Treasures specific to the awesome feature
|
+-- components  # Components, artisans sculpting the visual identity of the feature
|
+-- hooks       # Hooks, magical spells woven into the fabric of this feature
|
+-- routes      # Paths leading to the feature's pages, a roadmap of wonder
|
+-- stores      # Keepers of state, guarding the feature's sacred truths
|
+-- types       # TypeScript types, a lexicon for the feature's domain
|
+-- utils       # The craftsmen, building utility functions exclusive to this feature
|
+-- index.ts    # The grand entrance, the public API of this feature, revealing its essence
Enter fullscreen mode Exit fullscreen mode

索引文件

功能的所有内容都应从index.ts作为该功能的公共 API 的文件中导出。

图片描述注意每个组件文件夹的索引文件。⤴

您应该仅通过使用以下方式从其他功能导入内容:

import {AwesomeComponent} from "@/features/awesome-feature"

而不是

import {AwesomeComponent} from "@/features/awesome-feature/components/AwesomeComponent

设置绝对导入!

绝对导入可以使您的导入语句更简洁、更易读。它们还有助于避免冗长的相对导入路径。

//  jsconfig.json/tsconfig.json
"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
Enter fullscreen mode Exit fullscreen mode

记住,每个开发者,无论经验丰富还是初出茅庐,都曾与意大利面条式代码共舞过令人抓狂的探戈。但结构化带来清晰,清晰带来灵活运用 React 的力量。

因此,当你在前端开发领域开辟自己的道路时,让这份蓝图成为你的指路明灯,成为你通往井然有序的辉煌的藏宝图。愿你的 React 项目能够坦然面对 Bug,奚落混乱,并在编码灾难面前屹立不倒。


个人链接:
web
GitHub

脚注:
https://github.com/alan2207/bulletproof-react

文章来源:https://dev.to/phukon/how-i-struct-my-react-projects-1lk
PREV
使用 Docker 多阶段构建容器化 React 应用程序的另一种方法 TL;DR 准备让我们开始吧
NEXT
Zsh + Antigen + Oh my Zsh = 美观、强大、健壮的 Shell Zsh Antigen Oh my Zsh