본문 바로가기
IT/nextjs 기초 내 공부

쉬운 Nextjs 03 : 실전 라우팅 구현 가이드: 자동화까지

by higold 2024. 11. 12.
728x90

Next.js 실전 라우팅 구현 가이드: 자동화까지

목차

  1. 기본 개념과 용어
  2. 개발 주의사항
  3. 자동화 스크립트 구현

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>
  );
}

참고문헌

  1. Next.js 공식 문서. "Routing Fundamentals", https://nextjs.org/docs/app/building-your-application/routing
  2. Next.js 공식 문서. "Pages and Layouts", https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts
  3. Vercel Blog. "Next.js App Router Migration Guide", https://vercel.com/blog/next-js-app-router-migration-guide
  4. TypeScript 공식 문서. "File System APIs", https://www.typescriptlang.org/docs/handbook/fs.html
728x90