テックキャンプ卒の弱々エンジニア日記

エンジニアとして働く中での学びをちょっとでも記録していきます。

Reactのベストプラクティス(bulletproof-react)を知る

bulletproof-reactとは

bulletproof-reactはReactアプリ開発のベストプラクティスとして作られたリポジトリです。 シンプルでスケーラブルかつ強力なアーキテクチャを実現します。

github.com

その中でもディレクトリ構成がとても参考になるので 概要をまとめてみました

全体のディレクトリの構成

提案している全体の構成は下記のような感じです。

src
|
+-- assets            # assets folder can contain all the static files such as images, fonts, etc.
|
+-- components        # shared components used across the entire application
|
+-- config            # all the global configuration, env variables etc. get exported from here and used in the app
|
+-- features          # feature based modules
|
+-- hooks             # shared hooks used across the entire application
|
+-- lib               # re-exporting different libraries preconfigured for the application
|
+-- providers         # all of the application providers
|
+-- routes            # routes configuration
|
+-- stores            # global state stores
|
+-- test              # test utilities and mock server
|
+-- types             # base types used across the application
|
+-- utils             # shared utility functions

ほとんどのコードはsrcのフォルダー内に存在します。 このディレクトリ構成での一番の特徴としてはfeaturesになります。(実際大部分のコードをここに記載します)

このfeaturesは特定の機能、例えば顧客一覧・顧客詳細といった特定のドメインについてのコードが含まれます。 機能の範囲を限定することで、他の機能のソースコードと混在することなく管理することになります。 ファイル数が多くなればなるほど、よりその効果がわかるかと思います

featuresディレクトリ以下の構成

features以下のディレクトリ構成は以下のような構成になります。

// 例) 顧客詳細に関するディレクトリ構成の場合

src/features/user-detail
|
+-- api         # exported API request declarations and api hooks related to a specific feature
|
+-- assets      # assets folder can contain all the static files for a specific feature
|
+-- components  # components scoped to a specific feature
|
+-- hooks       # hooks scoped to a specific feature
|
+-- routes      # route components for a specific feature pages
|
+-- stores      # state stores for a specific feature
|
+-- types       # typescript types for TS specific feature domain
|
+-- utils       # utility functions for a specific feature
|
+-- index.ts    # entry point for the feature, it should serve as the public API of the given feature and exports everything that should be used outside the

全ての機能はindex.tsからエクスポートするようにします。 apiディレクトリでは例えば、GraphQLのクエリなどを定義するようにします。

assetsは画像など静的ファイルを格納しています。

componentsには、Viewに関するものだけをおきます。 フック関連のロジックに関してはhooksで管理します。

こんな感じでまとめていくと、 各ディレクトリごとに関心ごとをわけることができるので 開発がかなりしやすくなります。