728x90
Next.js 실전 라우팅 구현 가이드: 자동화까지
목차
1. 기본 개념과 용어
1.1 폴더 구조 기반 라우팅
Next.js는 트리 구조 기반의 라우팅을 사용합니다:
app/ (Root)
├── dashboard/ (Segment)
│ ├── settings/ (Segment)
│ │ └── page.tsx (Leaf)
│ └── page.tsx
└── page.tsx
- Tree (전체 구조):
app
폴더부터 시작하는 전체 폴더 구조 - Subtree (하위 구조): 특정 폴더 아래의 구조
- Root (루트): 최상위 폴더 (
app
) - Leaf (리프): 최하위
page.tsx
파일 - Segment: URL의 각 부분 (예:
/dashboard/settings
)
1.2 기본 라우팅 구현
// app/dashboard/page.tsx
export default function DashboardPage() {
return (
<div>
<h1>대시보드 페이지</h1>
</div>
);
}
2. 개발 주의사항
2.1 Pages Router와 App Router 동시 사용
// ❌ 잘못된 예시 (충돌 발생)
// pages/example.tsx
export default function Example() {
return <div>Pages Router</div>
}
// app/example/page.tsx
export default function Example() {
return <div>App Router</div>
}
// ✅ 올바른 예시
// pages/old-example.tsx
export default function OldExample() {
return <div>Pages Router</div>
}
// app/new-example/page.tsx
export default function NewExample() {
return <div>App Router</div>
}
2.2 컴포넌트 Colocation
app/
└─ dashboard/
├─ page.tsx // URL로 접근 가능
├─ components/ // URL로 접근 불가능
│ ├─ Header.tsx
│ └─ Sidebar.tsx
└─ utils/ // URL로 접근 불가능
└─ helpers.ts
3. 자동화 스크립트 구현
3.1 경로 상수 자동 생성기
// scripts/updatePaths.ts
import fs from 'fs';
import path from 'path';
interface FileList {
paths: string[];
}
// 설정
const ROOT_DIR = path.join(__dirname, '../src');
const APP_DIR = path.join(ROOT_DIR, 'app');
const CONSTANTS_FILE = path.join(ROOT_DIR, 'constants/paths.ts');
// 디렉토리 순회 함수
function traverseDirectory(dir: string, fileList: FileList): void {
const files = fs.readdirSync(dir);
files.forEach(file => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
traverseDirectory(fullPath, fileList);
} else if (file === 'page.tsx' || file === 'page.ts') {
const relativePath = fullPath
.replace(APP_DIR, '')
.replace(/\\/g, '/')
.replace(/\/page\.tsx?$/, '');
fileList.paths.push(relativePath);
}
});
}
// 상수명 생성 함수
function createConstantName(path: string): string {
return path
.replace(/^\//, '')
.replace(/\//g, '_')
.toUpperCase() + '_PATH';
}
// 메인 실행 함수
function updatePathConstants(): void {
const fileList: FileList = { paths: [] };
traverseDirectory(APP_DIR, fileList);
const constants = fileList.paths
.map(path => {
const name = createConstantName(path);
return `export const ${name} = '${path}';`;
})
.join('\n');
fs.writeFileSync(CONSTANTS_FILE, constants + '\n');
console.log('Path constants updated successfully!');
}
updatePathConstants();
3.2 생성된 상수 사용 예시
// constants/paths.ts (자동 생성된 파일)
export const DASHBOARD_PATH = '/dashboard';
export const DASHBOARD_SETTINGS_PATH = '/dashboard/settings';
// components/Navigation.tsx
import { DASHBOARD_PATH } from '@/constants/paths';
export default function Navigation() {
return (
<Link href={DASHBOARD_PATH}>
대시보드로 이동
</Link>
);
}
참고문헌
- Next.js 공식 문서. "Routing Fundamentals", https://nextjs.org/docs/app/building-your-application/routing
- Next.js 공식 문서. "Pages and Layouts", https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts
- Vercel Blog. "Next.js App Router Migration Guide", https://vercel.com/blog/next-js-app-router-migration-guide
- TypeScript 공식 문서. "File System APIs", https://www.typescriptlang.org/docs/handbook/fs.html
728x90
'IT > nextjs 기초 내 공부' 카테고리의 다른 글
쉬운 NextJS 06 : 'use client' 지시문과 페이지 렌더링 심층 분석 (0) | 2024.11.12 |
---|---|
쉬운 NextJs 05 : 서버 컴포넌트의 렌더링 프로세스 심층 분석 (0) | 2024.11.12 |
쉬운 NextJs 04: Layout 컴포넌트 완벽 가이드 - 제약사항과 해결방법 (1) | 2024.11.12 |
쉬운 Nextjs 02 : 라우팅 시스템 완벽 가이드 정의부터 장단점까지 (2) | 2024.11.12 |
쉬운 Next.js 01 : Nextjs의 등장 배경과 필요성: 프론트엔드 개발의 진화 (5) | 2024.11.12 |