我如何构建我的 React 项目
有没有想过,React 应用可以对 bug 嗤之以鼻,还能轻松应对意大利面条式代码?让我们踏上旅程,打造一个强大的 React 应用,让它能够经受住糟糕编码习惯的考验。
在那些新手的日子里,我的代码就像一头野兽——功能齐全,却又极其混乱。项目结构(如果可以这么称呼的话)简直是一团乱麻。这对于我最初的项目来说还算可以,但随着项目的发展,复杂性也随之增加,混乱随之而来。
经验丰富的开发者⤵
随着项目的每次扩展,查找特定的代码片段就像大海捞针一样困难,最终才发现这根针是代码深处某个地方的变量,名字很贴切,叫做“针”。
在你的代码库变成一本无法解开的神秘小说之前,花点时间学习如何构建你的 React 项目。
项目应该是这样的:
src
|
+-- assets
|
+-- components
|
+-- config
|
+-- features
|
+-- hooks
|
+-- lib
|
+-- providers
|
+-- routes
|
+-- stores
|
+-- test
|
+-- types
|
+-- utils
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
索引文件
功能的所有内容都应从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/*"]
}
}
记住,每个开发者,无论经验丰富还是初出茅庐,都曾与意大利面条式代码共舞过令人抓狂的探戈。但结构化带来清晰,清晰带来灵活运用 React 的力量。
因此,当你在前端开发领域开辟自己的道路时,让这份蓝图成为你的指路明灯,成为你通往井然有序的辉煌的藏宝图。愿你的 React 项目能够坦然面对 Bug,奚落混乱,并在编码灾难面前屹立不倒。
脚注:
https://github.com/alan2207/bulletproof-react