転職活動用のオリジナルアプリ開発をしています。
コンポーネントにAtomic Design
の考え方を学習しました。
さらに、『バレル構造』を導入することでコード管理がしやすくなりましたので
記録用にまとめます。
📌 はじめに
React
/ Next.js
プロジェクトでコンポーネントが増えてくると、import
のパスが長くなりがちです。
index.ts(バレルファイル)
を配置することで、import
を短縮・統一し、保守性を高めることができます。
今回は Atomic Design
構成(Atoms
/ Molecules
/ Organisms
)を前提に、
index.ts
の導入メリット・デメリットと導入手順を紹介します。
Atomic Design
に関しては別投稿にてまとめております!↓
📌 使用ツール
- Next.js (App Router)
- TypeScript
- VSCode
📌 階層例
作成中のオリジナルアプリを元に記載します。
-
components
直下にindex.ts
を格納 -
Atoms
/Molecules
/Organisms
各フォルダ直下にindex.ts
を格納
src/
app/
components/
atoms/
button/
Button.tsx
icon/
CategoryIcon.tsx
loading/
LoadingInSectionCard.tsx
text/
ErrorText.tsx
index.ts ◀︎ 導入
molecules/
field/
FormField.tsx
category/
CategoryItem.tsx
chart/
ProgressChart.tsx
section-card/
SectionCard.tsx
footer/
FooterItem.tsx
index.ts ◀︎ 導入
organisms/
header/
Header.tsx
footer/
Footer.tsx
goal/
GoalCard.tsx
add/
EditAddForm.tsx
session-error/
SessionError.tsx
index.ts ◀︎ 導入
index.ts ◀︎ 導入
📌 導入手順
1 ) 各レイヤーに index.ts
を作成
atoms / index.ts
// src/app/components/atoms/index.ts
export { default as Button } from "./button/Button";
export { default as CategoryIcon } from "./icon/CategoryIcon";
export { default as ErrorText } from "./text/ErrorText";
export { default as LoadingInSectionCard } from "./loading/LoadingInSectionCard";
molecules / index.ts
// src/app/components/molecules/index.ts
export { default as FormField } from "./field/FormField";
export { default as CategoryItem } from "./category/CategoryItem";
export { default as ProgressChart } from "./chart/ProgressChart";
export { default as SectionCard } from "./section-card/SectionCard";
organisms / index.ts
// src/app/components/organisms/index.ts
export { default as Header } from "./header/Header";
export { default as Footer } from "./footer/Footer";
export { default as GoalCard } from "./goal/GoalCard";
export { default as EditAddForm } from "./add/EditAddForm";
export { default as SessionError } from "./session-error/SessionError";
2 ) ルート components/index.ts
を作成
// src/app/components/index.ts
export * from "./atoms";
export * from "./molecules";
export * from "./organisms";
3 ) tsconfig.json
にパスエイリアスを設定
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components": ["src/app/components"],
"@atoms": ["src/app/components/atoms"],
"@molecules": ["src/app/components/molecules"],
"@organisms": ["src/app/components/organisms"]
}
}
}
上記のように記載することで、import分が短縮されます。
どこまで省略するかは調整してください。
Before
import Button from "../../../components/atoms/button/Button";
After
import { Button } from "@atoms";
3 ) import例
import { Button, FormField, GoalCard } from "@components";
📌 まとめ
-
index.ts
を置くとimport
が短く・統一される - リファクタに強く、内部構造を変えても呼び出し側は不変
- デメリットは 初期整備の手間 と 循環参照リスク
- 最小構成は「
atoms
/molecules
/organisms
にindex.ts
を置く」だけでOK!