all is well!!

02. next.js 라우팅 방식 본문

[Nextjs + Typescript] velog 클론코딩/[ Nextjs + Typescript ] 나를 위한 기록

02. next.js 라우팅 방식

tnqlscho 95 2023. 2. 1. 23:31

react에서는 App.js파일에 페이지 파일들을 이런식으로 <Route>에 path로 페이지 파일 위치를

일일히 작성해서 라우팅을 해주는 식이었는데..

next.js의 라우트 방식은 다른것 같아서 next.js docs를 참고해서 기록🥲

https://nextjs.org/docs/routing/introduction

 

Routing: Introduction | Next.js

Next.js has a built-in, opinionated, and file-system based Router. You can learn how it works here.

nextjs.org

 

1. index routes

next.js는 react와 다르게 index.js라고 이름이 지정된 파일을 자동 라우팅 해준다.

* pages/index.ts => / 

* pages/detail/index.ts => /detail

 

localhost에서 확인해보면 폴더와 파일을 만들기만 해도 이 경로를 참고해서 들어가보면

내가 원했던 페이지로 이동이 되었다.

 

폴더를 만들고 파일을 만들면 바로 자동 라우팅이 된다니...

react로만 연습해본 나한테는 생소하지만 너무 좋자냐..👀

react에 비해 route방식이 되게 간단해진것 같다..!

 

2. nested routes

하지만 항상 index.js라는 이름으로만 파일을 만들수없지..🥲

pages 폴더 안에 폴더를 더 만들어도 파일 이름을 바꾸어도 비슷한 방식으로 자동 라우팅 된다.

index.js대신 다른 이름으로 파일을 만들면 그 파일은 뒤에 생략하지 않고 붙여준다.

 

- pages/write/code.ts -> /write/code

- pages/write/setting/code.ts -> /write/setting/code

 

3. dynamic routes

제일 생소했던 dynamic route(동적 라우팅)

지정된 페이지 주소로만 라우팅 되는것이 아닌 사용자가 접근한 경로( 나에게는 어떤 mainpage의 게시글의 상세페이지 같은 경우..? 🧐)나 상황에 따라서 동적인 라우팅을 하고싶을때 사용한다고 한다.

지금 velog clonecoding에서는 카드들의 detail 페이지에 적용해보고 있다.

- pages/detail/[idx]/index.ts -> /detail/:idx

- pages/detail/[idx].ts -> /detail/:idx

- pages/detail/[idx]/blog.ts -> /detail/:idx/blog

- pages/post/[...all].js→ /post/*( /post/2020/id/title)

 

Comments