nextjs에서 제공하는 쇼핑몰을 샘플 소스를 분석해 보고 있는데 폴더마다 index.ts(=index.js) 파일이 있다. 거의 모든 폴더마다 index 파일이 있다. 폴더에 처음 접근했을 때 index 파일을 먼저 찾는건 알겠는데 왜 굳이 이 파일을 만들어 놓는 것일까? (index 파일은 같은 폴더의 파일을 import 하고 있었다. 하위에 폴더가 있으면 하위 폴더의 모든 파일을 imoprt 하고 있었다.)
/src
/components
/Avatar
Avatar.tsx
index.ts
/Register
Register.tsx
index.ts
index.ts
만약 index 파일과 상관없이 위의 components 폴더의 파일들을 import 하려면 아래와 같이 써 줘야 한다.
import Avatar from '/src/components/Avatar/Avatar';
import Register from '/src/components/Register/Register';
경로를 다 써줘야 하니 가독성이 안 좋다. 여러개의 파일을 import 할 수록 가독성은 떨어진다. 그러나 폴더마다 index 파일을 두면 간단해 진다.
import { Avatar, Register } from '/src/components';
해당 폴더를 갔을 때 index.ts를 먼저 찾는데 index.ts에서는 각 컴포넌트를 import 하고 있으니 필요한 컴포넌트를 가져다 쓸 수 있다. 한마디로 index.ts 파일은 목차 같은 역할을 수행한다. 이 구조는 nextjs, react 상관없이 똑같이 동작한다. 경로에 ‘/src/…’ 로 시작할 수 있는건 tsconfig.json 에 아래의 설정을 넣어줬기 때문에 가능하다.
{
"compilerOptions": {
"baseUrl": ".",
...
Main.tsx라는 컴포넌트에서 components 폴더의 파일을 import 하는 방법에 대해 알아보자.
- 파일 하나만 있을 때
/src
/main
Main.tsx
/components
Avatar.tsx
index.ts//src/components/index.ts
export { default } from './Avatar';//src/main/Main.tsx
import Avatar from '/src/components';
2. 파일 두 개 이상 있을 때
/src
/main
Main.tsx
/components
Avatar.tsx
index.ts//src/components/index.ts
export { default as Avatar } from './Avatar';
export { default as Register } from './Register';//src/main/Main.tsx
import { Avatar, Register } from '/src/components/';
index.ts에 default 를 두 개 이상 쓰면 에러가 발생하니 as 를 써 줘야 한다. 그리고 import 하는 쪽에서도 중괄호로 묶어줘야 한다.
3. 하위에 폴더가 있을 때
/src
/main
Main.tsx
/components
index.ts
/Avatar
Avatar.tsx
index.ts
/Register
Register.tsx
index.ts//src/components/index.ts
export { default as Avatar } from './Avatar';
export { default as Register } from './Register';//src/components/Avatar/Avatar.tsx
export { default } from './Avatar';//src/components/Register/Register
export { default } from './Register';//src/main/Main.tsx
import { Avatar, Register } from '/src/components/';