From 09f5832ca865ae071539d3edc1422ee2653b0bd7 Mon Sep 17 00:00:00 2001 From: Jinhyung Lee Date: Mon, 12 Aug 2024 14:10:40 +0900 Subject: [PATCH] =?UTF-8?q?[#6]=20docs:=208=EC=9B=94=202=EC=A3=BC=EC=B0=A8?= =?UTF-8?q?=20=EB=AC=B8=EC=84=9C=20=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8=20?= =?UTF-8?q?(#120)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [#90] docs: version-9 번역 (#101) * [#84] docs: getStaticProps 번역 (#106) * [#105] docs: amp 번역 (#107) * [#109] api-routes 번역 (#110) * [#86] docs: use-router.mdx 번역 (#113) * [#111] docs: pages-and-layouts 번역 (#114) * [#115] docs: image-legacy 번역 (#116) * [#89] docs: draft-mode 번역 (#117) * [#87] docs: internationalization 번역 (#118) * [#88] docs: getInitialProps 번역 (#119) * [#6] docs: 기여자 정보 추가 * [#115] docs: image-legacy 문법 수정 --------- Co-authored-by: Hyunsoo Kim Co-authored-by: grapefruit <92169354+grapefruit13@users.noreply.github.com> Co-authored-by: 박우빈 <102154880+Ubinquitous@users.noreply.github.com> Co-authored-by: Yoon Han Bin <69673803+kor-bim@users.noreply.github.com> Co-authored-by: 조민수 Co-authored-by: Jominsu Co-authored-by: HyojinLee Co-authored-by: Jinseung <127307160+wlstmd@users.noreply.github.com> Co-authored-by: Suhyeon Park <55135881+pySoo@users.noreply.github.com> Co-authored-by: vinnie Co-authored-by: Arin Co-authored-by: Jominsu --- .all-contributorsrc | 74 +++- README.md | 10 + .../api-reference/components/image-legacy.mdx | 339 +++++++++--------- .../functions/get-initial-props.mdx | 36 +- .../functions/get-static-props.mdx | 115 +++--- .../api-reference/functions/use-router.mdx | 168 +++++---- .../configuring/amp.mdx | 53 ++- .../configuring/draft-mode.mdx | 106 +++--- .../routing/api-routes.mdx | 150 ++++---- .../routing/internationalization.mdx | 144 ++++---- .../routing/pages-and-layouts.mdx | 42 ++- .../upgrading/version-9.mdx | 58 ++- pages/index.mdx | 138 +++++++ 13 files changed, 807 insertions(+), 626 deletions(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 3e9240c..4d01621 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -213,6 +213,78 @@ "contributions": [ "content" ] + }, + { + "login": "kor-bim", + "name": "Yoon Han Bin", + "avatar_url": "https://avatars.githubusercontent.com/u/69673803?v=4", + "profile": "https://github.com/kor-bim", + "contributions": [ + "content" + ] + }, + { + "login": "WaterMinCho", + "name": "조민수", + "avatar_url": "https://avatars.githubusercontent.com/u/74204327?v=4", + "profile": "https://github.com/WaterMinCho", + "contributions": [ + "content" + ] + }, + { + "login": "jinlee0310", + "name": "HyojinLee", + "avatar_url": "https://avatars.githubusercontent.com/u/177381010?v=4", + "profile": "https://github.com/jinlee0310", + "contributions": [ + "content" + ] + }, + { + "login": "davindev", + "name": "vinnie", + "avatar_url": "https://avatars.githubusercontent.com/u/67614188?v=4", + "profile": "https://velog.io/@davin", + "contributions": [ + "content" + ] + }, + { + "login": "hyunmyungJaneLee", + "name": "Arin", + "avatar_url": "https://avatars.githubusercontent.com/u/28864029?v=4", + "profile": "http://hyunmyungjanelee.github.io/blog", + "contributions": [ + "content" + ] + }, + { + "login": "wlstmd", + "name": "Jinseung", + "avatar_url": "https://avatars.githubusercontent.com/u/127307160?v=4", + "profile": "https://litt.ly/jinseung_", + "contributions": [ + "content" + ] + }, + { + "login": "mini-boo", + "name": "Hyunsoo Kim", + "avatar_url": "https://avatars.githubusercontent.com/u/81962257?v=4", + "profile": "https://velog.io/@mini-boo/posts", + "contributions": [ + "content" + ] + }, + { + "login": "Ubinquitous", + "name": "박우빈", + "avatar_url": "https://avatars.githubusercontent.com/u/102154880?v=4", + "profile": "https://parkubin.notion.site/a71d9b12489e4a93ab2d7c51b9b1e00b", + "contributions": [ + "content" + ] } ], "contributorsPerLine": 7, @@ -220,5 +292,5 @@ "repoType": "github", "repoHost": "https://github.com", "projectName": "nextjs-ko", - "projectOwner": "luciancah" + "projectOner": "luciancah" } diff --git a/README.md b/README.md index f63591b..527ed13 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,16 @@ Zero
Zero

🖋 Yoon Jeongyeon
Yoon Jeongyeon

🖋 + Yoon Han Bin
Yoon Han Bin

🖋 + 조민수
조민수

🖋 + HyojinLee
HyojinLee

🖋 + vinnie
vinnie

🖋 + Arin
Arin

🖋 + + + Jinseung
Jinseung

🖋 + Hyunsoo Kim
Hyunsoo Kim

🖋 + 박우빈
박우빈

🖋 diff --git a/pages/docs/pages/api-reference/components/image-legacy.mdx b/pages/docs/pages/api-reference/components/image-legacy.mdx index 36b0854..4dd0590 100644 --- a/pages/docs/pages/api-reference/components/image-legacy.mdx +++ b/pages/docs/pages/api-reference/components/image-legacy.mdx @@ -3,109 +3,107 @@ title: (Legacy) description: Backwards compatible Image Optimization with the Legacy Image component. --- -{/* TODO: 번역이 필요합니다. */} - -`` (Legacy) +# `` (Legacy)
- Examples + 예시 -- [Legacy Image Component](https://github.com/vercel/next.js/tree/canary/examples/image-legacy-component) +- [Legacy Image 컴포넌트](https://github.com/vercel/next.js/tree/canary/examples/image-legacy-component)
-Starting with Next.js 13, the `next/image` component was rewritten to improve both the performance and developer experience. In order to provide a backwards compatible upgrade solution, the old `next/image` was renamed to `next/legacy/image`. +Next.js 13부터 `next/image` 컴포넌트가 성능과 개발자 경험을 개선하기 위해 다시 작성되었습니다. 이전 버전과 호환되는 업그레이드 솔루션을 제공하기 위해 기존의 `next/image`는 `next/legacy/image`로 이름이 변경되었습니다. -View the **new** [`next/image` API Reference](/docs/pages/api-reference/components/image) +**새로운** [`next/image` API 참조](/docs/pages/api-reference/components/image)를 확인하세요. ## Comparison -Compared to `next/legacy/image`, the new `next/image` component has the following changes: +`next/legacy/image`와 비교하여 새로운 `next/image` 컴포넌트에는 다음과 같은 변경 사항이 있습니다: -- Removes `` wrapper around `` in favor of [native computed aspect ratio](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes) -- Adds support for canonical `style` prop - - Removes `layout` prop in favor of `style` or `className` - - Removes `objectFit` prop in favor of `style` or `className` - - Removes `objectPosition` prop in favor of `style` or `className` -- Removes `IntersectionObserver` implementation in favor of [native lazy loading](https://caniuse.com/loading-lazy-attr) - - Removes `lazyBoundary` prop since there is no native equivalent - - Removes `lazyRoot` prop since there is no native equivalent -- Removes `loader` config in favor of [`loader`](#loader) prop -- Changed `alt` prop from optional to required -- Changed `onLoadingComplete` callback to receive reference to `` element +- `` 주위의 `` 래퍼를 제거하고 [네이티브 계산 종횡비](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes)를 사용합니다 +- 표준 `style` prop 지원 추가 + - `layout` prop 대신 `style` 또는 `className` 사용 + - `objectFit` prop 대신 `style` 또는 `className` 사용 + - `objectPosition` prop 대신 `style` 또는 `className` 사용 +- `IntersectionObserver` 구현을 제거하고 [네이티브 지연 로딩](https://caniuse.com/loading-lazy-attr)을 사용합니다 + - 네이티브 대체품이 없으므로 `lazyBoundary` prop 제거 + - 네이티브 대체품이 없으므로 `lazyRoot` prop 제거 +- `loader` 설정 대신 [`loader`](#loader) prop 사용 +- `alt` prop을 선택 사항에서 필수로 변경 +- `onLoadingComplete` 콜백이 `` 요소에 대한 참조를 받도록 변경 ## Required Props -The `` component requires the following properties. +`` 컴포넌트에는 다음 속성이 필요합니다. ### src -Must be one of the following: +다음 중 하나여야 합니다: -- A [statically imported](/docs/pages/building-your-application/optimizing/images#local-images) image file -- A path string. This can be either an absolute external URL, or an internal path depending on the [loader](#loader) prop or [loader configuration](#loader-configuration). +- [정적으로 가져온](/docs/pages/building-your-application/optimizing/images#local-images) 이미지 파일 +- 경로 문자열. [loader](#loader) prop 또는 [loader 설정](#loader-configuration)에 따라 절대 외부 URL이나 내부 경로일 수 있습니다. -When using an external URL, you must add it to [remotePatterns](#remote-patterns) in `next.config.js`. +외부 URL을 사용할 때는 `next.config.js`의 [remotePatterns](#remote-patterns)에 추가해야 합니다. ### width -The `width` property can represent either the _rendered_ width or _original_ width in pixels, depending on the [`layout`](#layout) and [`sizes`](#sizes) properties. +`width` 속성은 [`layout`](#layout)과 [`sizes`](#sizes) 속성에 따라 _렌더링된_ 너비 또는 _원본_ 너비(픽셀 단위)를 나타낼 수 있습니다. -When using `layout="intrinsic"` or `layout="fixed"` the `width` property represents the _rendered_ width in pixels, so it will affect how large the image appears. +`layout="intrinsic"` 또는 `layout="fixed"`를 사용할 때 `width` 속성은 _렌더링된_ 너비(픽셀 단위)를 나타내므로 이미지가 표시되는 크기에 영향을 줍니다. -When using `layout="responsive"`, `layout="fill"`, the `width` property represents the _original_ width in pixels, so it will only affect the aspect ratio. +`layout="responsive"`, `layout="fill"`을 사용할 때 `width` 속성은 _원본_ 너비(픽셀 단위)를 나타내므로 종횡비에만 영향을 줍니다. -The `width` property is required, except for [statically imported images](/docs/pages/building-your-application/optimizing/images#local-images), or those with `layout="fill"`. +`width` 속성은 [정적으로 가져온 이미지](/docs/pages/building-your-application/optimizing/images#local-images)나 `layout="fill"`을 사용하는 경우를 제외하고 필수입니다. ### height -The `height` property can represent either the _rendered_ height or _original_ height in pixels, depending on the [`layout`](#layout) and [`sizes`](#sizes) properties. +`height` 속성은 [`layout`](#layout)과 [`sizes`](#sizes) 속성에 따라 _렌더링된_ 높이 또는 _원본_ 높이(픽셀 단위)를 나타낼 수 있습니다. -When using `layout="intrinsic"` or `layout="fixed"` the `height` property represents the _rendered_ height in pixels, so it will affect how large the image appears. +`layout="intrinsic"` 또는 `layout="fixed"`를 사용할 때 `height` 속성은 _렌더링된_ 높이(픽셀 단위)를 나타내므로 이미지가 표시되는 크기에 영향을 줍니다. -When using `layout="responsive"`, `layout="fill"`, the `height` property represents the _original_ height in pixels, so it will only affect the aspect ratio. +`layout="responsive"`, `layout="fill"`을 사용할 때 `height` 속성은 _원본_ 높이(픽셀 단위)를 나타내므로 종횡비에만 영향을 줍니다. -The `height` property is required, except for [statically imported images](/docs/pages/building-your-application/optimizing/images#local-images), or those with `layout="fill"`. +`height` 속성은 [정적으로 가져온 이미지](/docs/pages/building-your-application/optimizing/images#local-images)나 `layout="fill"`을 사용하는 경우를 제외하고 필수입니다. ## Optional Props -The `` component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the [Advanced Props](#advanced-props) section. +`` 컴포넌트는 필수 속성 외에도 여러 추가 속성을 허용합니다. 이 섹션에서는 Image 컴포넌트의 가장 일반적으로 사용되는 속성에 대해 설명합니다. 더 드물게 사용되는 속성에 대한 자세한 내용은 [고급 Props](#advanced-props) 섹션에서 확인할 수 있습니다. ### layout -The layout behavior of the image as the viewport changes size. - -| `layout` | Behavior | `srcSet` | `sizes` | Has wrapper and sizer | -| --------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------- | --------------------- | -| `intrinsic` (default) | Scale _down_ to fit width of container, up to image size | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A | yes | -| `fixed` | Sized to `width` and `height` exactly | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A | yes | -| `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | yes | -| `fill` | Grow in both X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | yes | - -- [Demo the `intrinsic` layout (default)](https://image-legacy-component.nextjs.gallery/layout-intrinsic) - - When `intrinsic`, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports. -- [Demo the `fixed` layout](https://image-legacy-component.nextjs.gallery/layout-fixed) - - When `fixed`, the image dimensions will not change as the viewport changes (no responsiveness) similar to the native `img` element. -- [Demo the `responsive` layout](https://image-legacy-component.nextjs.gallery/layout-responsive) - - When `responsive`, the image will scale the dimensions down for smaller viewports and scale up for larger viewports. - - Ensure the parent element uses `display: block` in their stylesheet. -- [Demo the `fill` layout](https://image-legacy-component.nextjs.gallery/layout-fill) - - When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative. - - This is usually paired with the [`objectFit`](#objectfit) property. - - Ensure the parent element has `position: relative` in their stylesheet. -- [Demo background image](https://image-legacy-component.nextjs.gallery/background) +뷰포트 크기가 변경됨에 따른 이미지의 레이아웃 동작입니다. + +| `layout` | 동작 | `srcSet` | `sizes` | 래퍼와 사이저 유무 | +| -------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------- | ------------------ | +| `intrinsic` (기본값) | 컨테이너 너비에 맞게 _축소_, 이미지 크기까지 | `1x`, `2x` ([imageSizes](#image-sizes) 기반) | N/A | 예 | +| `fixed` | `width`와 `height`에 정확히 맞춤 | `1x`, `2x` ([imageSizes](#image-sizes) 기반) | N/A | 예 | +| `responsive` | 컨테이너 너비에 맞게 조정 | `640w`, `750w`, ... `2048w`, `3840w` ([imageSizes](#image-sizes)와 [deviceSizes](#device-sizes) 기반) | `100vw` | 예 | +| `fill` | 컨테이너를 채우기 위해 X와 Y축 모두에서 확장 | `640w`, `750w`, ... `2048w`, `3840w` ([imageSizes](#image-sizes)와 [deviceSizes](#device-sizes) 기반) | `100vw` | 예 | + +- [`intrinsic` 레이아웃 데모 (기본값)](https://image-legacy-component.nextjs.gallery/layout-intrinsic) + - `intrinsic`일 때 이미지는 작은 뷰포트에서는 치수를 축소하지만 큰 뷰포트에서는 원래 치수를 유지합니다. +- [`fixed` 레이아웃 데모](https://image-legacy-component.nextjs.gallery/layout-fixed) + - `fixed`일 때 이미지 치수는 뷰포트가 변경되어도 변하지 않습니다(반응형 없음). 네이티브 `img` 요소와 유사합니다. +- [`responsive` 레이아웃 데모](https://image-legacy-component.nextjs.gallery/layout-responsive) + - `responsive`일 때 이미지는 작은 뷰포트에서는 치수를 축소하고 큰 뷰포트에서는 확대합니다. + - 부모 요소의 스타일시트에서 `display: block`을 사용해야 합니다. +- [`fill` 레이아웃 데모](https://image-legacy-component.nextjs.gallery/layout-fill) + - `fill`일 때 이미지는 부모 요소의 치수에 맞게 너비와 높이를 모두 늘립니다. 부모 요소는 상대적이어야 합니다. + - 일반적으로 [`objectFit`](#objectfit) 속성과 함께 사용됩니다. + - 부모 요소의 스타일시트에 `position: relative`가 있어야 합니다. +- [배경 이미지 데모](https://image-legacy-component.nextjs.gallery/background) ### loader -A custom function used to resolve URLs. Setting the loader as a prop on the Image component overrides the default loader defined in the [`images` section of `next.config.js`](#loader-configuration). +URL을 해석하는 데 사용되는 사용자 정의 함수입니다. Image 컴포넌트에 loader를 prop으로 설정하면 [`next.config.js`의 `images` 섹션](#loader-configuration)에 정의된 기본 loader를 재정의합니다. -A `loader` is a function returning a URL string for the image, given the following parameters: +`loader`는 다음 매개변수를 받아 이미지의 URL 문자열을 반환하는 함수입니다: - [`src`](#src) - [`width`](#width) - [`quality`](#quality) -Here is an example of using a custom loader: +다음은 사용자 정의 loader를 사용하는 예시입니다: ```js import Image from 'next/legacy/image' @@ -129,15 +127,15 @@ const MyImage = (props) => { ### sizes -A string that provides information about how wide the image will be at different breakpoints. The value of `sizes` will greatly affect performance for images using `layout="responsive"` or `layout="fill"`. It will be ignored for images using `layout="intrinsic"` or `layout="fixed"`. +이미지가 다양한 브레이크포인트에서 얼마나 넓게 표시될지를 제공하는 문자열입니다. `sizes`의 값은 `layout="responsive"` 또는 `layout="fill"`을 사용하는 이미지의 성능에 큰 영향을 미칩니다. `layout="intrinsic"` 또는 `layout="fixed"`를 사용하는 이미지에는 무시됩니다. -The `sizes` property serves two important purposes related to image performance: +`sizes` 속성은 이미지 성능과 관련하여 두 가지 중요한 목적을 수행합니다: -First, the value of `sizes` is used by the browser to determine which size of the image to download, from `next/legacy/image`'s automatically-generated source set. When the browser chooses, it does not yet know the size of the image on the page, so it selects an image that is the same size or larger than the viewport. The `sizes` property allows you to tell the browser that the image will actually be smaller than full screen. If you don't specify a `sizes` value, a default value of `100vw` (full screen width) is used. +첫째, `sizes`의 값은 브라우저가 `next/legacy/image`의 자동 생성된 소스 세트에서 다운로드할 이미지의 크기를 결정하는 데 사용됩니다. 브라우저가 선택할 때 페이지에서 이미지의 크기를 아직 알지 못하므로 뷰포트와 같은 크기 또는 더 큰 이미지를 선택합니다. `sizes` 속성을 사용하면 브라우저에 이미지가 실제로 전체 화면보다 작을 것임을 알릴 수 있습니다. `sizes` 값을 지정하지 않으면 기본값인 `100vw`(전체 화면 너비)가 사용됩니다. -Second, the `sizes` value is parsed and used to trim the values in the automatically-created source set. If the `sizes` property includes sizes such as `50vw`, which represent a percentage of the viewport width, then the source set is trimmed to not include any values which are too small to ever be necessary. +둘째, `sizes` 값은 구문 분석되어 자동 생성된 소스 세트의 값을 조정하는 데 사용됩니다. `sizes` 속성에 `50vw`와 같은 뷰포트 너비의 비율을 나타내는 크기가 포함되면, 소스 세트는 필요할 수 없는 너무 작은 값을 포함하지 않도록 조정됩니다. -For example, if you know your styling will cause an image to be full-width on mobile devices, in a 2-column layout on tablets, and a 3-column layout on desktop displays, you should include a sizes property such as the following: +예를 들어, 스타일링으로 인해 모바일 장치에서 이미지를 전체 너비로 표시하고, 태블릿에서는 2열 레이아웃, 데스크탑 디스플레이에서는 3열 레이아웃이 될 것임을 알고 있다면, 다음과 같은 `sizes` 속성을 포함해야 합니다: ```js import Image from 'next/legacy/image' @@ -154,37 +152,37 @@ const Example = () => ( ) ``` -This example `sizes` could have a dramatic effect on performance metrics. Without the `33vw` sizes, the image selected from the server would be 3 times as wide as it needs to be. Because file size is proportional to the square of the width, without `sizes` the user would download an image that's 9 times larger than necessary. +이 예제의 `sizes`는 성능 지표에 극적인 영향을 미칠 수 있습니다. `33vw` 크기가 없으면 서버에서 선택된 이미지는 필요 이상으로 3배 넓어질 것입니다. 파일 크기는 너비의 제곱에 비례하므로, `sizes`가 없으면 사용자는 필요 이상으로 9배 큰 이미지를 다운로드하게 됩니다. -Learn more about `srcset` and `sizes`: +`srcset` 및 `sizes`에 대해 더 알아보세요: - [web.dev](https://web.dev/learn/design/responsive-images/#sizes) - [mdn](https://developer.mozilla.org/docs/Web/HTML/Element/img#attr-sizes) ### quality -The quality of the optimized image, an integer between `1` and `100` where `100` is the best quality. Defaults to `75`. +최적화된 이미지의 품질로, `1`에서 `100` 사이의 정수이며 `100`이 최고의 품질입니다. 기본값은 `75`입니다. ### priority -When true, the image will be considered high priority and -[preload](https://web.dev/preload-responsive-images/). Lazy loading is automatically disabled for images using `priority`. +true일 경우, 이미지는 높은 우선순위로 간주되며 +[preload](https://web.dev/preload-responsive-images/)됩니다. `priority`를 사용하는 이미지는 Lazy loading이 자동으로 비활성화됩니다. -You should use the `priority` property on any image detected as the [Largest Contentful Paint (LCP)](https://nextjs.org/learn/seo/web-performance/lcp) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes. +[Largest Contentful Paint (LCP)](https://nextjs.org/learn/seo/web-performance/lcp) 요소로 감지된 모든 이미지에 `priority` 속성을 사용해야 합니다. 서로 다른 이미지가 서로 다른 뷰포트 크기에서 LCP 요소가 될 수 있으므로 여러 개의 우선순위 이미지를 갖는 것이 적절할 수 있습니다. -Should only be used when the image is visible above the fold. Defaults to `false`. +이미지가 화면에 보일 때만 사용해야 합니다. 기본값은 `false`입니다. ### placeholder -A placeholder to use while the image is loading. Possible values are `blur` or `empty`. Defaults to `empty`. +이미지가 로딩되는 동안 사용할 플레이스홀더입니다. 가능한 값은 `blur` 또는 `empty`이며, 기본값은 `empty`입니다. -When `blur`, the [`blurDataURL`](#blurdataurl) property will be used as the placeholder. If `src` is an object from a [static import](/docs/pages/building-your-application/optimizing/images#local-images) and the imported image is `.jpg`, `.png`, `.webp`, or `.avif`, then `blurDataURL` will be automatically populated. +`blur`인 경우, [`blurDataURL`](#blurdataurl) 속성이 플레이스홀더로 사용됩니다. `src`가 [정적 가져오기](/docs/pages/building-your-application/optimizing/images#local-images)에서 가져온 객체이고, 가져온 이미지가 `.jpg`, `.png`, `.webp`, 또는 `.avif`일 경우, `blurDataURL`이 자동으로 채워집니다. -For dynamic images, you must provide the [`blurDataURL`](#blurdataurl) property. Solutions such as [Plaiceholder](https://github.com/joe-bell/plaiceholder) can help with `base64` generation. +동적 이미지의 경우, [`blurDataURL`](#blurdataurl) 속성을 제공해야 합니다. `base64` 생성에 도움이 되는 솔루션으로는 [Plaiceholder](https://github.com/joe-bell/plaiceholder)가 있습니다. -When `empty`, there will be no placeholder while the image is loading, only empty space. +`empty`인 경우, 이미지가 로딩되는 동안 플레이스홀더가 없으며, 빈 공간만 표시됩니다. -Try it out: +다음과 같이 시도해 보세요: - [Demo the `blur` placeholder](https://image-legacy-component.nextjs.gallery/placeholder) - [Demo the shimmer effect with `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/shimmer) @@ -192,86 +190,80 @@ Try it out: ## Advanced Props -In some cases, you may need more advanced usage. The `` component optionally accepts the following advanced properties. +일부 경우에는 더 고급 사용이 필요할 수 있습니다. `` 컴포넌트는 선택적으로 다음과 같은 고급 속성을 수용합니다. ### style -Allows [passing CSS styles](https://developer.mozilla.org/docs/Web/HTML/Element/style) to the underlying image element. +기본 이미지 요소에 [CSS 스타일을 전달](https://developer.mozilla.org/docs/Web/HTML/Element/style)할 수 있습니다. -Note that all `layout` modes apply their own styles to the image element, and these automatic styles take precedence over the `style` prop. +모든 `layout` 모드는 이미지 요소에 고유한 스타일을 적용하며, 이러한 자동 스타일이 `style` prop보다 우선합니다. -Also keep in mind that the required `width` and `height` props can interact with your styling. If you use styling to modify an image's `width`, you must set the `height="auto"` style as well, or your image will be distorted. +또한 필수 `width` 및 `height` 속성이 스타일과 상호작용할 수 있음을 기억하세요. 이미지를 수정하기 위해 스타일링을 사용하는 경우, `height="auto"` 스타일도 설정해야 하며, 그렇지 않으면 이미지가 왜곡될 수 있습니다. ### objectFit -Defines how the image will fit into its parent container when using `layout="fill"`. +`layout="fill"`을 사용할 때 이미지가 부모 컨테이너에 어떻게 맞춰질지를 정의합니다. -This value is passed to the [object-fit CSS property](https://developer.mozilla.org/docs/Web/CSS/object-fit) for the `src` image. +이 값은 `src` 이미지의 [object-fit CSS 속성](https://developer.mozilla.org/docs/Web/CSS/object-fit)으로 전달됩니다. ### objectPosition -Defines how the image is positioned within its parent element when using `layout="fill"`. +`layout="fill"`을 사용할 때 이미지가 부모 요소 내에서 어떻게 위치하는지를 정의합니다. -This value is passed to the [object-position CSS property](https://developer.mozilla.org/docs/Web/CSS/object-position) applied to the image. +이 값은 이미지에 적용되는 [object-position CSS 속성](https://developer.mozilla.org/docs/Web/CSS/object-position)으로 전달됩니다. ### onLoadingComplete -A callback function that is invoked once the image is completely loaded and the [placeholder](#placeholder) has been removed. +이미지가 완전히 로드되고 [플레이스홀더](#placeholder)가 제거된 후 호출되는 콜백 함수입니다. -The `onLoadingComplete` function accepts one parameter, an object with the following properties: +`onLoadingComplete` 함수는 다음 속성을 가진 객체를 하나의 매개변수로 받습니다: - [`naturalWidth`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/naturalWidth) - [`naturalHeight`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/naturalHeight) ### loading -> **Attention**: This property is only meant for advanced usage. Switching an -> image to load with `eager` will normally **hurt performance**. +> **주의**: 이 속성은 고급 사용을 위한 것입니다. 이미지를 `eager`로 전환하면 일반적으로 **성능에 악영향**을 미칩니다. > -> We recommend using the [`priority`](#priority) property instead, which -> properly loads the image eagerly for nearly all use cases. +> 대부분의 사용 사례에 대해 이미지를 적절하게 즉시 로드하려면 [`priority`](#priority) 속성을 사용하는 것이 좋습니다. -The loading behavior of the image. Defaults to `lazy`. +이미지의 로딩 동작입니다. 기본값은 `lazy`입니다. -When `lazy`, defer loading the image until it reaches a calculated distance from -the viewport. +`lazy`일 경우, 이미지가 뷰포트에서 계산된 거리까지 도달할 때까지 로딩을 연기합니다. -When `eager`, load the image immediately. +`eager`일 경우, 이미지를 즉시 로드합니다. -[Learn more](https://developer.mozilla.org/docs/Web/HTML/Element/img#attr-loading) +[자세히 알아보기](https://developer.mozilla.org/docs/Web/HTML/Element/img#attr-loading) ### blurDataURL -A [Data URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) to -be used as a placeholder image before the `src` image successfully loads. Only takes effect when combined -with [`placeholder="blur"`](#placeholder). +`src` 이미지가 성공적으로 로드되기 전에 플레이스홀더 이미지로 사용되는 [데이터 URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)입니다. [`placeholder="blur"`](#placeholder)와 결합할 때만 효과를 발휘합니다. -Must be a base64-encoded image. It will be enlarged and blurred, so a very small image (10px or -less) is recommended. Including larger images as placeholders may harm your application performance. +반드시 base64로 인코딩된 이미지여야 합니다. 확대되고 블러 처리되므로, 매우 작은 이미지(10px 이하)가 권장됩니다. 더 큰 이미지를 플레이스홀더로 포함하면 애플리케이션 성능에 악영향을 미칠 수 있습니다. -Try it out: +다음과 같이 시도해 보세요: - [Demo the default `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/placeholder) - [Demo the shimmer effect with `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/shimmer) - [Demo the color effect with `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/color) -You can also [generate a solid color Data URL](https://png-pixel.com) to match the image. +이미지에 맞는 고유 색상 데이터 URL을 [생성할 수도 있습니다](https://png-pixel.com). ### lazyBoundary -A string (with similar syntax to the margin property) that acts as the bounding box used to detect the intersection of the viewport with the image and trigger lazy [loading](#loading). Defaults to `"200px"`. +이미지와 뷰포트의 교차를 감지하고 lazy [로딩](#loading)을 트리거하는 데 사용되는 경계 상자로, margin 속성과 유사한 구문을 가진 문자열입니다. 기본값은 `"200px"`입니다. -If the image is nested in a scrollable parent element other than the root document, you will also need to assign the [lazyRoot](#lazyroot) prop. +이미지가 루트 문서가 아닌 스크롤 가능한 부모 요소에 중첩된 경우, [lazyRoot](#lazyroot) 속성도 할당해야 합니다. -[Learn more](https://developer.mozilla.org/docs/Web/API/IntersectionObserver/rootMargin) +[자세히 알아보기](https://developer.mozilla.org/docs/Web/API/IntersectionObserver/rootMargin) ### lazyRoot -A React [Ref](https://react.dev/learn/referencing-values-with-refs) pointing to the scrollable parent element. Defaults to `null` (the document viewport). +스크롤 가능한 부모 요소를 가리키는 React [Ref](https://react.dev/learn/referencing-values-with-refs)입니다. 기본값은 `null`(문서 뷰포트)입니다. -The Ref must point to a DOM element or a React component that [forwards the Ref](https://react.dev/reference/react/forwardRef) to the underlying DOM element. +Ref는 DOM 요소 또는 [Ref를 전달하는](https://react.dev/reference/react/forwardRef) React 컴포넌트를 가리켜야 합니다. -**Example pointing to a DOM element** +**DOM 요소를 가리키는 예시** ```jsx import Image from 'next/legacy/image' @@ -289,7 +281,7 @@ const Example = () => { } ``` -**Example pointing to a React component** +**React 컴포넌트를 가리키는 예시** ```jsx import Image from 'next/legacy/image' @@ -315,12 +307,11 @@ const Example = () => { } ``` -[Learn more](https://developer.mozilla.org/docs/Web/API/IntersectionObserver/root) +[자세히 알아보기](https://developer.mozilla.org/docs/Web/API/IntersectionObserver/root) ### unoptimized -When true, the source image will be served as-is instead of changing quality, -size, or format. Defaults to `false`. +`true`일 경우, 소스 이미지는 품질, 크기 또는 형식을 변경하지 않고 그대로 제공됩니다. 기본값은 `false`입니다. ```js import Image from 'next/image' @@ -330,7 +321,7 @@ const UnoptimizedImage = (props) => { } ``` -Since Next.js 12.3.0, this prop can be assigned to all images by updating `next.config.js` with the following configuration: +Next.js 12.3.0부터 이 속성은 다음과 같은 구성으로 next.config.js를 업데이트하여 모든 이미지에 적용할 수 있습니다: ```js filename="next.config.js" module.exports = { @@ -342,20 +333,17 @@ module.exports = { ## Other Props -Other properties on the `` component will be passed to the underlying -`img` element with the exception of the following: +`` 컴포넌트의 다른 속성은 다음을 제외하고 기본 `img` 요소로 전달됩니다: -- `srcSet`. Use - [Device Sizes](#device-sizes) - instead. -- `ref`. Use [`onLoadingComplete`](#onloadingcomplete) instead. -- `decoding`. It is always `"async"`. +- `srcSet`. 대신 [Device Sizes](#device-sizes)를 사용하세요. +- `ref`. 대신 [`onLoadingComplete`](#onloadingcomplete)를 사용하세요. +- `decoding`. 항상 `"async"`입니다. ## Configuration Options ### Remote Patterns -To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below: +악의적인 사용자로부터 애플리케이션을 보호하기 위해 외부 이미지를 사용하려면 구성이 필요합니다. 이를 통해 귀하의 계정에서 제공되는 외부 이미지만 Next.js 이미지 최적화 API에서 제공될 수 있습니다. 이러한 외부 이미지는 `next.config.js` 파일의 `remotePatterns` 속성으로 구성할 수 있습니다. 아래와 같이 설정하세요: ```js filename="next.config.js" module.exports = { @@ -372,9 +360,8 @@ module.exports = { } ``` -> **Good to know**: The example above will ensure the `src` property of `next/legacy/image` must start with `https://example.com/account123/`. Any other protocol, hostname, port, or unmatched path will respond with 400 Bad Request. - -Below is another example of the `remotePatterns` property in the `next.config.js` file: +> **알아두면 좋은 점**: 위의 예시는 `next/legacy/image`의 `src` 속성이 `https://example.com/account123/`로 시작해야 함을 보장합니다. 다른 프로토콜, 호스트 이름, 포트 또는 일치하지 않는 경로는 400 Bad Request 응답을 받게 됩니다. +> 다음은 `next.config.js` 파일의 `remotePatterns` 속성에 대한 또 다른 예시입니다: ```js filename="next.config.js" module.exports = { @@ -390,26 +377,26 @@ module.exports = { } ``` -> **Good to know**: The example above will ensure the `src` property of `next/legacy/image` must start with `https://img1.example.com` or `https://me.avatar.example.com` or any number of subdomains. Any other protocol, port, or unmatched hostname will respond with 400 Bad Request. +> **알아두면 좋은 점**: 위의 예시는 `next/legacy/image`의 `src` 속성이 `https://img1.example.com` 또는 `https://me.avatar.example.com` 또는 여러 개의 서브도메인으로 시작해야 함을 보장합니다. 다른 프로토콜, 포트 또는 일치하지 않는 호스트 이름은 400 Bad Request 응답을 받게 됩니다. -Wildcard patterns can be used for both `pathname` and `hostname` and have the following syntax: +와일드카드 패턴은 `pathname`과 `hostname` 모두에 사용될 수 있으며, 다음과 같은 구문을 가집니다: -- `*` match a single path segment or subdomain -- `**` match any number of path segments at the end or subdomains at the beginning +- `*`는 단일 경로 세그먼트 또는 서브도메인과 일치 +- `**`는 끝의 여러 경로 세그먼트 또는 시작의 서브도메인과 일치 -The `**` syntax does not work in the middle of the pattern. +`**` 구문은 패턴의 중간에 사용될 수 없습니다. -> **Good to know**: When omitting `protocol`, `port` or `pathname`, then the wildcard `**` is implied. This is not recommended because it may allow malicious actors to optimize urls you did not intend. +> **알아두면 좋은 점**: `protocol`, `port` 또는 `pathname`을 생략하면 와일드카드 `**`가 암묵적으로 적용됩니다. 이는 악의적인 사용자가 의도하지 않은 URL을 최적화할 수 있으므로 권장되지 않습니다. ### Domains -> **Warning**: Deprecated since Next.js 14 in favor of strict [`remotePatterns`](#remote-patterns) in order to protect your application from malicious users. Only use `domains` if you own all the content served from the domain. +> **경고**: Next.js 14부터 악의적인 사용자로부터 애플리케이션을 보호하기 위해 엄격한 [`remotePatterns`](#remote-patterns) 사용을 권장합니다. 도메인에서 제공되는 모든 콘텐츠를 소유한 경우에만 `domains`를 사용하세요. -Similar to [`remotePatterns`](#remote-patterns), the `domains` configuration can be used to provide a list of allowed hostnames for external images. +[`remotePatterns`](#remote-patterns)와 유사하게, `domains` 구성은 외부 이미지에 대한 허용된 호스트 이름 목록을 제공하는 데 사용할 수 있습니다. -However, the `domains` configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname. +그러나 `domains` 구성은 와일드카드 패턴 매칭을 지원하지 않으며, 프로토콜, 포트 또는 경로를 제한할 수 없습니다. -Below is an example of the `domains` property in the `next.config.js` file: +다음은 `next.config.js` 파일의 `domains` 속성에 대한 예시입니다: ```js filename="next.config.js" module.exports = { @@ -421,7 +408,7 @@ module.exports = { ### Loader Configuration -If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the `loader` and `path` prefix in your `next.config.js` file. This allows you to use relative URLs for the Image [`src`](#src) and automatically generate the correct absolute URL for your provider. +Next.js 내장 이미지 최적화 API 대신 클라우드 제공업체를 사용하여 이미지를 최적화하려면 `next.config.js` 파일에서 `loader`와 `path` 접두사를 구성할 수 있습니다. 이를 통해 이미지의 [`src`](#src)에 상대 URL을 사용할 수 있으며, 제공업체에 맞는 올바른 절대 URL이 자동으로 생성됩니다. ```js filename="next.config.js" module.exports = { @@ -434,28 +421,28 @@ module.exports = { ### Built-in Loaders -The following Image Optimization cloud providers are included: +다음의 이미지 최적화 클라우드 제공업체가 포함되어 있습니다: -- Default: Works automatically with `next dev`, `next start`, or a custom server -- [Vercel](https://vercel.com): Works automatically when you deploy on Vercel, no configuration necessary. [Learn more](https://vercel.com/docs/concepts/image-optimization?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) +- 기본: `next dev`, `next start` 또는 커스텀 서버에서 자동으로 작동합니다. +- [Vercel](https://vercel.com): Vercel에 배포할 때 자동으로 작동하며, 별도의 구성 필요 없습니다. [자세히 알아보기](https://vercel.com/docs/concepts/image-optimization?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) - [Imgix](https://www.imgix.com): `loader: 'imgix'` - [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'` - [Akamai](https://www.akamai.com): `loader: 'akamai'` -- Custom: `loader: 'custom'` use a custom cloud provider by implementing the [`loader`](#loader) prop on the `next/legacy/image` component +- 커스텀: `loader: 'custom'`를 사용하여 `next/legacy/image` 컴포넌트의 [`loader`](#loader) 속성을 구현하여 커스텀 클라우드 제공업체를 사용할 수 있습니다. -If you need a different provider, you can use the [`loader`](#loader) prop with `next/legacy/image`. +다른 제공업체가 필요하면 `next/legacy/image`와 함께 [`loader`](#loader) 속성을 사용할 수 있습니다. -> Images can not be optimized at build time using [`output: 'export'`](/docs/pages/building-your-application/deploying/static-exports), only on-demand. To use `next/legacy/image` with `output: 'export'`, you will need to use a different loader than the default. [Read more in the discussion.](https://github.com/vercel/next.js/discussions/19065) +> 이미지 최적화는 빌드 시간에 [`output: 'export'`](/docs/pages/building-your-application/deploying/static-exports)로 사용할 수 없으며, 온디맨드에서만 가능합니다. `output: 'export'`와 함께 `next/legacy/image`를 사용하려면 기본 로더와 다른 로더를 사용해야 합니다. [토론 내용을 더 읽어보세요.](https://github.com/vercel/next.js/discussions/19065) ## Advanced -The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates. +다음 구성은 고급 사용 사례에 해당하며 일반적으로 필요하지 않습니다. 아래 속성을 구성하기로 선택하면 향후 업데이트에서 Next.js 기본값에 대한 변경 사항이 무시됩니다. ### Device Sizes -If you know the expected device widths of your users, you can specify a list of device width breakpoints using the `deviceSizes` property in `next.config.js`. These widths are used when the `next/legacy/image` component uses `layout="responsive"` or `layout="fill"` to ensure the correct image is served for user's device. +사용자의 예상 디바이스 너비를 알고 있다면, `next.config.js`의 `deviceSizes` 속성을 사용하여 디바이스 너비 브레이크포인트 목록을 지정할 수 있습니다. 이러한 너비는 `next/legacy/image` 컴포넌트가 `layout="responsive"` 또는 `layout="fill"`을 사용할 때 사용자 디바이스에 맞는 올바른 이미지가 제공되도록 하는 데 사용됩니다. -If no configuration is provided, the default below is used. +구성이 제공되지 않으면 아래의 기본값이 사용됩니다. ```js filename="next.config.js" module.exports = { @@ -467,11 +454,11 @@ module.exports = { ### Image Sizes -You can specify a list of image widths using the `images.imageSizes` property in your `next.config.js` file. These widths are concatenated with the array of [device sizes](#device-sizes) to form the full array of sizes used to generate image [srcset](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/srcset)s. +`next.config.js` 파일에서 `images.imageSizes` 속성을 사용하여 이미지 너비 목록을 지정할 수 있습니다. 이러한 너비는 [디바이스 사이즈](#device-sizes) 배열과 결합되어 이미지 [srcset](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/srcset)를 생성하는 데 사용되는 전체 사이즈 배열을 형성합니다. -The reason there are two separate lists is that imageSizes is only used for images which provide a [`sizes`](#sizes) prop, which indicates that the image is less than the full width of the screen. **Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.** +두 개의 별도 목록이 있는 이유는 `imageSizes`가 [`sizes`](#sizes) 속성을 제공하는 이미지에만 사용되기 때문입니다. 이 속성은 이미지가 화면의 전체 너비보다 작다는 것을 나타냅니다. **따라서 `imageSizes`의 사이즈는 모두 `deviceSizes`의 가장 작은 사이즈보다 작아야 합니다.** -If no configuration is provided, the default below is used. +구성이 제공되지 않으면 아래의 기본값이 사용됩니다. ```js filename="next.config.js" module.exports = { @@ -483,11 +470,11 @@ module.exports = { ### Acceptable Formats -The default [Image Optimization API](#loader-configuration) will automatically detect the browser's supported image formats via the request's `Accept` header. +기본 [이미지 최적화 API](#loader-configuration)는 요청의 `Accept` 헤더를 통해 브라우저에서 지원하는 이미지 포맷을 자동으로 감지합니다. -If the `Accept` head matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match (or the source image is [animated](#animated-images)), the Image Optimization API will fallback to the original image's format. +`Accept` 헤더가 구성된 포맷 중 하나와 일치하면 배열에서 첫 번째 일치 항목이 사용됩니다. 따라서 배열의 순서가 중요합니다. 일치하는 항목이 없거나(또는 소스 이미지가 [애니메이션](#animated-images)인 경우) 이미지 최적화 API는 원본 이미지의 포맷으로 되돌아갑니다. -If no configuration is provided, the default below is used. +구성이 제공되지 않으면 아래의 기본값이 사용됩니다. ```js filename="next.config.js" module.exports = { @@ -497,7 +484,7 @@ module.exports = { } ``` -You can enable AVIF support with the following configuration. +AVIF 지원을 다음 구성으로 활성화할 수 있습니다. ```js filename="next.config.js" module.exports = { @@ -507,29 +494,29 @@ module.exports = { } ``` -> **Good to know**: AVIF generally takes 20% longer to encode but it compresses 20% smaller compared to WebP. This means that the first time an image is requested, it will typically be slower and then subsequent requests that are cached will be faster. +> **알아두면 좋은 점**: AVIF는 일반적으로 인코딩에 20% 더 오랜 시간이 걸리지만, WebP에 비해 20% 더 작은 크기로 압축됩니다. 이는 이미지를 처음 요청할 때 일반적으로 느리지만, 이후 캐시된 요청은 더 빨라진다는 것을 의미합니다. ## Caching Behavior -The following describes the caching algorithm for the default [loader](#loader). For all other loaders, please refer to your cloud provider's documentation. +다음은 기본 [로더](#loader)에 대한 캐싱 알고리즘을 설명합니다. 다른 모든 로더에 대해서는 클라우드 제공업체의 문서를 참조하세요. -Images are optimized dynamically upon request and stored in the `/cache/images` directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the expired image is served stale immediately. Then the image is optimized again in the background (also called revalidation) and saved to the cache with the new expiration date. +이미지는 요청 시 동적으로 최적화되어 `/cache/images` 디렉토리에 저장됩니다. 최적화된 이미지 파일은 만료될 때까지 이후 요청에 대해 제공됩니다. 만약 캐시된 파일이 만료되었지만 요청이 들어오면, 만료된 이미지는 즉시 오래된 상태로 제공됩니다. 이후 이미지는 백그라운드에서 다시 최적화(재검증이라고도 함)되어 새로운 만료 날짜와 함께 캐시에 저장됩니다. -The cache status of an image can be determined by reading the value of the `x-nextjs-cache` (`x-vercel-cache` when deployed on Vercel) response header. The possible values are the following: +이미지의 캐시 상태는 `x-nextjs-cache`(`Vercel에 배포된 경우 `x-vercel-cache`) 응답 헤더의 값을 읽음으로써 확인할 수 있습니다. 가능한 값은 다음과 같습니다: -- `MISS` - the path is not in the cache (occurs at most once, on the first visit) -- `STALE` - the path is in the cache but exceeded the revalidate time so it will be updated in the background -- `HIT` - the path is in the cache and has not exceeded the revalidate time +- `MISS` - 경로가 캐시에 없음 (최초 방문 시 최대 한 번 발생) +- `STALE` - 경로가 캐시에 있지만 재검증 시간을 초과하여 백그라운드에서 업데이트될 예정 +- `HIT` - 경로가 캐시에 있으며 재검증 시간을 초과하지 않음 -The expiration (or rather Max Age) is defined by either the [`minimumCacheTTL`](#minimum-cache-ttl) configuration or the upstream image `Cache-Control` header, whichever is larger. Specifically, the `max-age` value of the `Cache-Control` header is used. If both `s-maxage` and `max-age` are found, then `s-maxage` is preferred. The `max-age` is also passed-through to any downstream clients including CDNs and browsers. +만료(또는 최대 연령)는 [`minimumCacheTTL`](#minimum-cache-ttl) 구성이나 상위 이미지의 `Cache-Control` 헤더 중 더 큰 값으로 정의됩니다. 구체적으로, `Cache-Control` 헤더의 `max-age` 값이 사용됩니다. `s-maxage`와 `max-age`가 모두 발견되면 `s-maxage`가 우선시됩니다. `max-age`는 CDN 및 브라우저를 포함한 모든 다운스트림 클라이언트에도 전달됩니다. -- You can configure [`minimumCacheTTL`](#minimum-cache-ttl) to increase the cache duration when the upstream image does not include `Cache-Control` header or the value is very low. -- You can configure [`deviceSizes`](#device-sizes) and [`imageSizes`](#image-sizes) to reduce the total number of possible generated images. -- You can configure [formats](#acceptable-formats) to disable multiple formats in favor of a single image format. +- 상위 이미지에 `Cache-Control` 헤더가 포함되어 있지 않거나 값이 매우 낮을 경우, [`minimumCacheTTL`](#minimum-cache-ttl)을 구성하여 캐시 기간을 늘릴 수 있습니다. +- [`deviceSizes`](#device-sizes) 및 [`imageSizes`](#image-sizes)를 구성하여 생성 가능한 이미지의 총 수를 줄일 수 있습니다. +- [formats](#acceptable-formats)를 구성하여 여러 포맷을 비활성화하고 단일 이미지 포맷을 사용할 수 있습니다. ### Minimum Cache TTL -You can configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a [Static Image Import](/docs/pages/building-your-application/optimizing/images#local-images) which will automatically hash the file contents and cache the image forever with a `Cache-Control` header of `immutable`. +캐시된 최적화된 이미지의 생존 시간(TTL)을 초 단위로 구성할 수 있습니다. 많은 경우, [정적 이미지 가져오기](/docs/pages/building-your-application/optimizing/images#local-images)를 사용하는 것이 더 좋습니다. 이 방법은 파일 내용을 자동으로 해시하고 `immutable`의 `Cache-Control` 헤더로 이미지를 영구적으로 캐시합니다. ```js filename="next.config.js" module.exports = { @@ -539,19 +526,19 @@ module.exports = { } ``` -The expiration (or rather Max Age) of the optimized image is defined by either the `minimumCacheTTL` or the upstream image `Cache-Control` header, whichever is larger. +최적화된 이미지의 만료(또는 최대 연령)는 `minimumCacheTTL` 또는 상위 이미지의 `Cache-Control` 헤더 중 더 큰 값으로 정의됩니다. -If you need to change the caching behavior per image, you can configure [`headers`](/docs/pages/api-reference/next-config-js/headers) to set the `Cache-Control` header on the upstream image (e.g. `/some-asset.jpg`, not `/_next/image` itself). +이미지마다 캐싱 동작을 변경해야 할 경우, [`headers`](/docs/pages/api-reference/next-config-js/headers)를 구성하여 상위 이미지에 `Cache-Control` 헤더를 설정할 수 있습니다(예: `/some-asset.jpg`, `/_next/image` 자체는 아님). -There is no mechanism to invalidate the cache at this time, so its best to keep `minimumCacheTTL` low. Otherwise you may need to manually change the [`src`](#src) prop or delete `/cache/images`. +현재 캐시를 무효화하는 메커니즘은 없으므로 `minimumCacheTTL`을 낮게 유지하는 것이 좋습니다. 그렇지 않으면 [`src`](#src) 속성을 수동으로 변경하거나 `/cache/images`를 삭제해야 할 수도 있습니다. ### Disable Static Imports -The default behavior allows you to import static files such as `import icon from './icon.png'` and then pass that to the `src` property. +기본 동작은 `import icon from './icon.png'`와 같은 정적 파일을 가져온 후 이를 `src` 속성에 전달할 수 있게 해줍니다. -In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently. +경우에 따라, 가져오기가 다르게 동작하기를 기대하는 다른 플러그인과 충돌할 경우 이 기능을 비활성화하고 싶을 수 있습니다. -You can disable static image imports inside your `next.config.js`: +정적 이미지 가져오기를 `next.config.js` 내에서 비활성화할 수 있습니다. ```js filename="next.config.js" module.exports = { @@ -563,11 +550,11 @@ module.exports = { ### Dangerously Allow SVG -The default [loader](#loader) does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/app/api-reference/next-config-js/headers#content-security-policy). +기본 [로더](#loader)는 몇 가지 이유로 SVG 이미지를 최적화하지 않습니다. 첫째, SVG는 벡터 형식으로 손실 없이 크기를 조절할 수 있습니다. 둘째, SVG는 HTML/CSS와 유사한 많은 기능을 가지고 있어 적절한 [콘텐츠 보안 정책(CSP) 헤더](/docs/app/api-reference/next-config-js/headers#content-security-policy)가 없으면 취약점이 발생할 수 있습니다. -Therefore, we recommended using the [`unoptimized`](#unoptimized) prop when the [`src`](#src) prop is known to be SVG. This happens automatically when `src` ends with `".svg"`. +따라서 [`src`](#src) 속성이 SVG임이 확실할 때는 [`unoptimized`](#unoptimized) 속성을 사용하는 것이 좋습니다. 이는 `src`가 `".svg"`로 끝날 때 자동으로 발생합니다. -However, if you need to serve SVG images with the default Image Optimization API, you can set `dangerouslyAllowSVG` inside your `next.config.js`: +그러나 기본 이미지 최적화 API로 SVG 이미지를 제공해야 하는 경우, `next.config.js` 내에서 `dangerouslyAllowSVG`를 설정할 수 있습니다: ```js filename="next.config.js" module.exports = { @@ -579,15 +566,15 @@ module.exports = { } ``` -In addition, it is strongly recommended to also set `contentDispositionType` to force the browser to download the image, as well as `contentSecurityPolicy` to prevent scripts embedded in the image from executing. +또한, 브라우저가 이미지를 다운로드하도록 강제하기 위해 `contentDispositionType`을 설정하고, 이미지에 포함된 스크립트가 실행되지 않도록 `contentSecurityPolicy`를 설정하는 것이 강력히 권장됩니다. ### `contentDispositionType` -The default [loader](#loader) sets the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_response_header_for_the_main_body) header to `attachment` for added protection since the API can serve arbitrary remote images. +기본 [로더](#loader)는 추가 보호를 위해 [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_response_header_for_the_main_body) 헤더를 `attachment`로 설정합니다. API는 임의의 원격 이미지를 제공할 수 있기 때문입니다. -The default value is `attachment` which forces the browser to download the image when visiting directly. This is particularly important when [`dangerouslyAllowSVG`](#dangerously-allow-svg) is true. +기본 값은 `attachment`로, 이를 통해 브라우저는 직접 방문할 때 이미지를 다운로드하도록 강제됩니다. 이는 [`dangerouslyAllowSVG`](#dangerously-allow-svg)가 true일 때 특히 중요합니다. -You can optionally configure `inline` to allow the browser to render the image when visiting directly, without downloading it. +선택적으로 `inline`을 구성하여 브라우저가 직접 방문할 때 이미지를 다운로드하지 않고 렌더링할 수 있도록 할 수 있습니다. ```js filename="next.config.js" module.exports = { @@ -599,9 +586,9 @@ module.exports = { ### Animated Images -The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is. +기본 [로더](#loader)는 애니메이션 이미지에 대해 자동으로 이미지 최적화를 우회하고 이미지를 있는 그대로 제공합니다. -Auto-detection for animated files is best-effort and supports GIF, APNG, and WebP. If you want to explicitly bypass Image Optimization for a given animated image, use the [unoptimized](#unoptimized) prop. +애니메이션 파일에 대한 자동 감지는 최선의 노력으로 이루어지며 GIF, APNG 및 WebP를 지원합니다. 특정 애니메이션 이미지에 대해 명시적으로 이미지 최적화를 우회하고 싶다면 [unoptimized](#unoptimized) 속성을 사용하세요. ## Version History diff --git a/pages/docs/pages/api-reference/functions/get-initial-props.mdx b/pages/docs/pages/api-reference/functions/get-initial-props.mdx index 492cfd3..4252ab2 100644 --- a/pages/docs/pages/api-reference/functions/get-initial-props.mdx +++ b/pages/docs/pages/api-reference/functions/get-initial-props.mdx @@ -3,13 +3,11 @@ title: getInitialProps description: Fetch dynamic data on the server for your React component with getInitialProps. --- -{/* TODO: 번역이 필요합니다. */} - # getInitialProps -> **Good to know**: `getInitialProps` is a legacy API. We recommend using [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props) or [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props) instead. +> **알아두기** : `getInitialProps`는 레거시 API입니다. 대신 [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props) 또는 [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props)를 사용하는 것이 좋습니다. -`getInitialProps` is an `async` function that can be added to the default exported React component for the page. It will run on both the server-side and again on the client-side during page transitions. The result of the function will be forwarded to the React component as `props`. +`getInitialProps`는 페이지에 기본적으로 내보내지는 React 컴포넌트에 추가할 수 있는 `비동기` 함수입니다. 이 함수는 서버 사이드와 클라이언트 사이드의 페이지 전환 시 모두 실행됩니다. 함수의 결과는 React 컴포넌트에 `props`로 전달됩니다. ```tsx filename="pages/index.tsx" switcher import { NextPageContext } from 'next' @@ -37,26 +35,26 @@ export default function Page({ stars }) { } ``` -> **Good to know**: +> **알아두기**: > -> - Data returned from `getInitialProps` is serialized when server rendering. Ensure the returned object from `getInitialProps` is a plain `Object`, and not using `Date`, `Map` or `Set`. -> - For the initial page load, `getInitialProps` will run on the server only. `getInitialProps` will then also run on the client when navigating to a different route with the [`next/link`](/docs/pages/api-reference/components/link) component or by using [`next/router`](/docs/pages/api-reference/functions/use-router). -> - If `getInitialProps` is used in a custom `_app.js`, and the page being navigated to is using `getServerSideProps`, then `getInitialProps` will also run on the server. +> - `getInitialProps`에서 반환된 데이터는 서버 렌더링 시 직렬화됩니다. `getInitialProps`에서 반환하는 객체는 단순한 `Object`여야 하며, `Date`, `Map`, `Set` 같은 객체를 사용하지 않아야 합니다. +> - 초기 페이지 로드 시, `getInitialProps`는 서버에서만 실행됩니다. 이후에는 [`next/link`](/docs/pages/api-reference/components/link) 컴포넌트나 [`next/router`](/docs/pages/api-reference/functions/use-router)를 사용하여 다른 경로로 이동할 때 클라이언트에서도 `getInitialProps`가 실행됩니다. +> - `getInitialProps`가 사용자 정의 `_app.js`에서 사용되며, 이동하려는 페이지가 `getServerSideProps`를 사용하는 경우, `getInitialProps`는 서버에서도 실행됩니다. ## Context Object -`getInitialProps` receives a single argument called `context`, which is an object with the following properties: +`getInitialProps`는 `context`라는 단일 인자를 받습니다. 이 `context`는 다음과 같은 속성을 가진 객체입니다: -| Name | Description | -| ---------- | ----------------------------------------------------------------------------------------------------- | -| `pathname` | Current route, the path of the page in `/pages` | -| `query` | Query string of the URL, parsed as an object | -| `asPath` | `String` of the actual path (including the query) shown in the browser | -| `req` | [HTTP request object](https://nodejs.org/api/http.html#http_class_http_incomingmessage) (server only) | -| `res` | [HTTP response object](https://nodejs.org/api/http.html#http_class_http_serverresponse) (server only) | -| `err` | Error object if any error is encountered during the rendering | +| 이름 | 설명 | +| ---------- | ---------------------------------------------------------------------------------------------- | +| `pathname` | 현재 경로, `/pages` 디렉토리 내의 페이지 경로 | +| `query` | URL의 쿼리 문자열을 객체로 파싱한 값 | +| `asPath` | 브라우저에 표시되는 실제 경로(query 포함)의 `문자열` | +| `req` | [HTTP 요청 객체](https://nodejs.org/api/http.html#http_class_http_incomingmessage) (서버 전용) | +| `res` | [HTTP 응답 객체](https://nodejs.org/api/http.html#http_class_http_serverresponse) (서버 전용) | +| `err` | 렌더링 중 오류가 발생할 경우 오류 객체 | ## Caveats -- `getInitialProps` can only be used in `pages/` top level files, and not in nested components. To have nested data fetching at the component level, consider exploring the [App Router](/docs/app/building-your-application/data-fetching). -- Regardless of whether your route is static or dynamic, any data returned from `getInitialProps` as `props` will be able to be examined on the client-side in the initial HTML. This is to allow the page to be [hydrated](https://react.dev/reference/react-dom/hydrate) correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in `props`. +- `getInitialProps`는 `pages/` 디렉토리의 최상위 파일에서만 사용할 수 있으며, 중첩된 컴포넌트에서는 사용할 수 없습니다. 컴포넌트 수준에서 중첩된 데이터 가져오기를 하려면 [App Router](/docs/app/building-your-application/data-fetching)를 참고해 보세요. +- 경로가 정적이든 동적이든 상관없이, `getInitialProps`에서 반환된 데이터는 초기 HTML에서 클라이언트 단에서 확인할 수 있습니다. 이는 페이지가 [hydrated](https://react.dev/reference/react-dom/hydrate)될 수 있도록 하기 위해서입니다. 클라이언트에서 접근하면 안 되는 민감한 정보는 `props`에 포함되지 않도록 주의하세요. diff --git a/pages/docs/pages/api-reference/functions/get-static-props.mdx b/pages/docs/pages/api-reference/functions/get-static-props.mdx index 1847552..170a861 100644 --- a/pages/docs/pages/api-reference/functions/get-static-props.mdx +++ b/pages/docs/pages/api-reference/functions/get-static-props.mdx @@ -3,11 +3,9 @@ title: getStaticProps description: API reference for `getStaticProps`. Learn how to use `getStaticProps` to generate static pages with Next.js. --- -{/* TODO: 번역이 필요합니다. */} - # getStaticProps -Exporting a function called `getStaticProps` will pre-render a page at build time using the props returned from the function: +`getStaticProps`라는 함수를 내보내면, 함수에서 반환된 props를 사용하여 빌드 시점에 페이지를 사전 렌더링합니다: ```tsx filename="pages/index.tsx" switcher import type { InferGetStaticPropsType, GetStaticProps } from 'next' @@ -44,47 +42,48 @@ export default function Page({ repo }) { } ``` -You can import modules in top-level scope for use in `getStaticProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including fetching data from your database. +`getStaticProps`에서 사용하기위해 모듈을 최상위 스코프에서 import 할 수 있습니다. 사용된 import는 **클라이언트 측 번들에 포함되지 않습니다**. 이는 **서버 측 코드를 `getStaticProps`에서 직접** 작성할 수 있다는 것을 의미하며, 여기에는 데이터베이스에서 데이터를 가져오는 작업이 포함됩니다. ## Context parameter -The `context` parameter is an object containing the following keys: +`context` 매개변수는 다음 키를 포함하는 객체입니다: -| Name | Description | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `params` | Contains the route parameters for pages using [dynamic routes](/docs/pages/building-your-application/routing/dynamic-routes). For example, if the page name is `[id].js`, then `params` will look like `{ id: ... }`. You should use this together with `getStaticPaths`, which we'll explain later. | -| `preview` | (Deprecated for `draftMode`) `preview` is `true` if the page is in the [Preview Mode](/docs/pages/building-your-application/configuring/preview-mode) and `false` otherwise. | -| `previewData` | (Deprecated for `draftMode`) The [preview](/docs/pages/building-your-application/configuring/preview-mode) data set by `setPreviewData`. | -| `draftMode` | `draftMode` is `true` if the page is in the [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode) and `false` otherwise. | -| `locale` | Contains the active locale (if enabled). | -| `locales` | Contains all supported locales (if enabled). | -| `defaultLocale` | Contains the configured default locale (if enabled). | -| `revalidateReason` | Provides a reason for why the function was called. Can be one of: "build" (run at build time), "stale" (revalidate period expired, or running in [development mode](/docs/pages/building-your-application/data-fetching/get-static-props#runs-on-every-request-in-development)), "on-demand" (triggered via [on-demand revalidation](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation)) | +| 이름 | 설명 | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `params` | [동적 경로](/docs/pages/building-your-application/routing/dynamic-routes)를 사용하는 페이지의 경로 매개변수를 포함합니다. 예를 들어, 페이지 이름이 `[id].js`인 경우, `params`는 `{ id: ... }`와 같습니다. 이는 나중에 설명할 `getStaticPaths`와 함께 사용해야 합니다. | +| `preview` | (`draftMode`에서는 더 이상 사용되지 않습니다.) 페이지가 [미리 보기 모드](/docs/pages/building-your-application/configuring/preview-mode)일 경우 `true`이고, 그렇지 않을 경우 `false`입니다. | +| `previewData` | (`draftMode`에서는 더 이상 사용되지 않습니다.) `setPreviewData`에 의해 설정된 [미리 보기](/docs/pages/building-your-application/configuring/preview-mode) 데이터입니다. | +| `draftMode` | 페이지가 [Draft Mode](/docs/pages/building-your-application/configuring/draft-mode)일 경우 `true`이고, 그렇지 않을 경우 `false`입니다. | +| `locale` | 활성화된 로케일을 포함합니다 (활성화된 경우). | +| `locales` | 지원하는 모든 로케일을 포함합니다 (활성화된 경우). | +| `defaultLocale` | 구성된 기본 로케일을 포함합니다 (활성화된 경우). | +| `revalidateReason` | 함수가 호출된 이유를 제공합니다. 다음 중 하나일 수 있습니다: "build" (빌드 시점에 실행), "stale" (재검증 기간 만료 또는 [개발 모드](/docs/pages/building-your-application/data-fetching/get-static-props#runs-on-every-request-in-development)에서 실행), "on-demand" ([온디맨드 재검증](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation)을 통해 트리거됨) | ## getStaticProps return values -The `getStaticProps` function should return an object containing either `props`, `redirect`, or `notFound` followed by an **optional** `revalidate` property. +`getStaticProps` 함수는 선택적 `revalidate` 프로퍼티와 함께 `props`, `redirect` 또는 `notFound`가 포함된 객체를 반환해야 합니다. ### `props` -The `props` object is a key-value pair, where each value is received by the page component. It should be a [serializable object](https://developer.mozilla.org/docs/Glossary/Serialization) so that any props passed, could be serialized with [`JSON.stringify`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). +`props` 객체는 키-값 쌍으로, 각 값은 페이지 컴포넌트에서 받습니다. +전달된 모든 props들이 [`JSON.stringify`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)로 직렬화될 수 있도록, 이 값은 [직렬화 가능한 객체](https://developer.mozilla.org/docs/Glossary/Serialization)여야 합니다. ```jsx export async function getStaticProps(context) { return { - props: { message: `Next.js is awesome` }, // will be passed to the page component as props + props: { message: `Next.js is awesome` }, // 이 값은 페이지 컴포넌트에 props로 전달됩니다. } } ``` ### `revalidate` -The `revalidate` property is the amount in seconds after which a page re-generation can occur (defaults to `false` or no revalidation). +`revalidate` 프로퍼티는 페이지가 재생성되는 시간(초)입니다(기본값은 'false' 또는 재검증 없음). ```js -// This function gets called at build time on server-side. -// It may be called again, on a serverless function, if -// revalidation is enabled and a new request comes in +// 이 함수는 서버 측에서 빌드 시점에 호출됩니다. +// 재검증이 활성화되고 새로운 요청이 들어오는 경우, 서버리스 함수에서 다시 호출될 수 있습니다. + export async function getStaticProps() { const res = await fetch('https://.../posts') const posts = await res.json() @@ -93,25 +92,25 @@ export async function getStaticProps() { props: { posts, }, - // Next.js will attempt to re-generate the page: - // - When a request comes in - // - At most once every 10 seconds - revalidate: 10, // In seconds + // Next.js는 페이지 재생성을 시도합니다: + // - 요청이 들어올 때 + // - 최대 10초마다 한 번씩 + revalidate: 10, // 초 단위 } } ``` -Learn more about [Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration). +[ISR](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)에 대해 자세히 알아보세요. -The cache status of a page leveraging ISR can be determined by reading the value of the `x-nextjs-cache` response header. The possible values are the following: +ISR을 활용하는 페이지의 캐시 상태는 `x-nextjs-cache` 응답 헤더의 값을 읽어서 확인할 수 있습니다. 가능한 값은 다음과 같습니다: -- `MISS` - the path is not in the cache (occurs at most once, on the first visit) -- `STALE` - the path is in the cache but exceeded the revalidate time so it will be updated in the background -- `HIT` - the path is in the cache and has not exceeded the revalidate time +- `MISS` - 경로가 캐시에 없습니다. (첫 방문 시 최대 한 번 발생) +- `STALE` - 경로가 캐시에 있지만, 재검증 시간을 초과하여 백그라운드에서 업데이트될 예정입니다. +- `HIT` - 경로가 캐시에 있고, 재검증 시간을 초과하지 않았습니다. ### `notFound` -The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/pages/building-your-application/routing/custom-error#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author. Note, `notFound` follows the same `revalidate` behavior [described here](#revalidate). +`notFound` boolean은 페이지가 `404` 상태를 반환하도록 하며 [404 페이지](/docs/pages/building-your-application/routing/custom-error#404-page)를 표시합니다. `notFound: true`로 설정하면, 이전에 성공적으로 생성된 페이지가 있더라도 페이지는 `404`를 반환합니다. 이는 사용자 생성한 콘텐츠가 작성자에 의해 삭제되는 등의 사용 사례를 지원하기 위한 것입니다. `notFound`는 [여기 설명된 것](#revalidate)과 동일한 `revalidate` 동작을 따름에 주의하세요. ```js export async function getStaticProps(context) { @@ -125,18 +124,18 @@ export async function getStaticProps(context) { } return { - props: { data }, // will be passed to the page component as props + props: { data }, // 프로퍼티로 페이지 컴포넌트에 전달됩니다. } } ``` -> **Good to know**: `notFound` is not needed for [`fallback: false`](/docs/pages/api-reference/functions/get-static-paths#fallback-false) mode as only paths returned from `getStaticPaths` will be pre-rendered. +> **알아두면 좋은 점** : [`fallback: false`](/docs/pages/api-reference/functions/get-static-paths#fallback-false) 모드에서는 `getStaticPaths`에서 반환된 경로만 사전 렌더링되므로 `notFound`가 필요하지 않습니다. ### `redirect` -The `redirect` object allows redirecting to internal or external resources. It should match the shape of `{ destination: string, permanent: boolean }`. +`redirect` 객체는 내부 또는 외부 리소스로 리디렉션할 수 있게 해줍니다. 이는 `{ destination: string, permanent: boolean }`의 형태와 일치해야 합니다. -In some rare cases, you might need to assign a custom status code for older `HTTP` clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, **but not both**. You can also set `basePath: false` similar to redirects in `next.config.js`. +드물게, 구형 `HTTP` 클라이언트가 올바르게 리디렉션되도록 사용자 정의 상태 코드를 할당해야 하는 경우가 있습니다. 이러한 경우 `permanent` 프로퍼티 대신 `statusCode` 프로퍼티를 사용할 수 있지만, **두 가지를 동시에 사용할 수는 없습니다**. 또한 `next.config.js`에서 리디렉션과 유사하게 `basePath: false`를 설정할 수 있습니다. ```js export async function getStaticProps(context) { @@ -154,28 +153,28 @@ export async function getStaticProps(context) { } return { - props: { data }, // will be passed to the page component as props + props: { data }, // 프로퍼티로 페이지 컴포넌트에 전달됩니다. } } ``` -If the redirects are known at build-time, they should be added in [`next.config.js`](/docs/pages/api-reference/next-config-js/redirects) instead. +리디렉션이 빌드 시점에 알려진 경우, [`next.config.js`](/docs/pages/api-reference/next-config-js/redirects)에 추가해야 합니다. ## Reading files: Use `process.cwd()` -Files can be read directly from the filesystem in `getStaticProps`. +파일은 `getStaticProps`의 파일시스템에서 직접 읽혀질 수 있습니다. -In order to do so you have to get the full path to a file. +이렇게 하려면 파일의 전체 경로를 가져와야 합니다. -Since Next.js compiles your code into a separate directory you can't use `__dirname` as the path it returns will be different from the Pages Router. +Next.js는 코드를 별도의 디렉토리로 컴파일하기 때문에 `__dirname`을 사용할 수 없습니다. `__dirname`이 반환하는 경로는 페이지 라우터와 다를 수 있기 때문입니다. -Instead you can use `process.cwd()` which gives you the directory where Next.js is being executed. +대신 `process.cwd()`를 사용할 수 있으며, 이는 Next.js가 실행되는 디렉토리를 제공합니다. ```jsx import { promises as fs } from 'fs' import path from 'path' -// posts will be populated at build time by getStaticProps() +// 게시물은 빌드 시점에 getStaticProps()에 의해 채워집니다. function Blog({ posts }) { return (
    @@ -189,9 +188,8 @@ function Blog({ posts }) { ) } -// This function gets called at build time on server-side. -// It won't be called on client-side, so you can even do -// direct database queries. +// 이 함수는 서버 측에서 빌드 시 호출됩니다. +// 클라이언트 측에서는 호출되지 않으므로 직접 데이터베이스 쿼리를 수행할 수도 있습니다. export async function getStaticProps() { const postsDirectory = path.join(process.cwd(), 'posts') const filenames = await fs.readdir(postsDirectory) @@ -200,16 +198,15 @@ export async function getStaticProps() { const filePath = path.join(postsDirectory, filename) const fileContents = await fs.readFile(filePath, 'utf8') - // Generally you would parse/transform the contents - // For example you can transform markdown to HTML here + // 일반적으로 콘텐츠를 파싱/변환할 수 있습니다. + // 예를 들어 여기에서 마크다운을 HTML로 변환할 수 있습니다. return { filename, content: fileContents, } }) - // By returning { props: { posts } }, the Blog component - // will receive `posts` as a prop at build time + // { props: { posts }를 반환하면, 블로그 컴포넌트는 빌드 시점에 'posts'를 prop으로 받습니다. return { props: { posts: await Promise.all(posts), @@ -222,12 +219,12 @@ export default Blog ## Version History -| Version | Changes | -| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `v13.4.0` | [App Router](/docs/app/building-your-application/data-fetching) is now stable with simplified data fetching | -| `v12.2.0` | [On-Demand Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation) is stable. | -| `v12.1.0` | [On-Demand Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation) added (beta). | -| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. | -| `v10.0.0` | `fallback: 'blocking'` return option added. | -| `v9.5.0` | Stable [Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) | -| `v9.3.0` | `getStaticProps` introduced. | +| 버전 | 변경 사항 | +| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `v13.4.0` | [앱 라우터](/docs/app/building-your-application/data-fetching)가 데이터 페칭 단순화된 상태로 안정화되었습니다. | +| `v12.2.0` | [온디맨드 ISR](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation)이 안정화되었습니다. | +| `v12.1.0` | [온디맨드 ISR](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation)이 추가되었습니다(베타). | +| `v10.0.0` | `locale`, `locales`, `defaultLocale`, `notFound` 옵션이 추가되었습니다. | +| `v10.0.0` | `fallback: 'blocking'` 반환 옵션이 추가 되었습니다. | +| `v9.5.0` | [ISR](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)이 안정화되었습니다. | +| `v9.3.0` | `getStaticProps`가 도입되었습니다. | diff --git a/pages/docs/pages/api-reference/functions/use-router.mdx b/pages/docs/pages/api-reference/functions/use-router.mdx index d75efdc..a9d93f2 100644 --- a/pages/docs/pages/api-reference/functions/use-router.mdx +++ b/pages/docs/pages/api-reference/functions/use-router.mdx @@ -3,11 +3,9 @@ title: useRouter description: Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook. --- -{/* TODO: 번역이 필요합니다. */} - # useRouter -If you want to access the [`router` object](#router-object) inside any function component in your app, you can use the `useRouter` hook, take a look at the following example: +앱의 모든 함수 컴포넌트 내에서 [`router` Object](#router-object)에 액세스하려면 `useRouter` 훅을 사용할 수 있습니다. 다음 예를 살펴보세요. ```jsx import { useRouter } from 'next/router' @@ -34,46 +32,46 @@ function ActiveLink({ children, href }) { export default ActiveLink ``` -> `useRouter` is a [React Hook](https://react.dev/learn#using-hooks), meaning it cannot be used with classes. You can either use [withRouter](#withrouter) or wrap your class in a function component. +> `useRouter`는 [React Hook](https://react.dev/learn#using-hooks)으로, 클래스와 함께 사용할 수 없습니다. [withRouter](#withrouter)를 사용하거나 클래스를 함수 컴포넌트로 감싸야 합니다. ## `router` object -The following is the definition of the `router` object returned by both [`useRouter`](#top) and [`withRouter`](#withrouter): +다음은 [`useRouter`](#top) 및 [`withRouter`](#withrouter)에서 반환된 router 객체의 정의입니다: -- `pathname`: `String` - The path for current route file that comes after `/pages`. Therefore, `basePath`, `locale` and trailing slash (`trailingSlash: true`) are not included. -- `query`: `Object` - The query string parsed to an object, including [dynamic route](/docs/pages/building-your-application/routing/dynamic-routes) parameters. It will be an empty object during prerendering if the page doesn't use [Server-side Rendering](/docs/pages/building-your-application/data-fetching/get-server-side-props). Defaults to `{}` -- `asPath`: `String` - The path as shown in the browser including the search params and respecting the `trailingSlash` configuration. `basePath` and `locale` are not included. -- `isFallback`: `boolean` - Whether the current page is in [fallback mode](/docs/pages/api-reference/functions/get-static-paths#fallback-true). -- `basePath`: `String` - The active [basePath](/docs/app/api-reference/next-config-js/basePath) (if enabled). -- `locale`: `String` - The active locale (if enabled). -- `locales`: `String[]` - All supported locales (if enabled). -- `defaultLocale`: `String` - The current default locale (if enabled). -- `domainLocales`: `Array<{domain, defaultLocale, locales}>` - Any configured domain locales. -- `isReady`: `boolean` - Whether the router fields are updated client-side and ready for use. Should only be used inside of `useEffect` methods and not for conditionally rendering on the server. See related docs for use case with [automatically statically optimized pages](/docs/pages/building-your-application/rendering/automatic-static-optimization) -- `isPreview`: `boolean` - Whether the application is currently in [preview mode](/docs/pages/building-your-application/configuring/preview-mode). +- `pathname`: `String` - `/pages` 이후의 현재 경로 파일입니다. 따라서 `basePath`, `locale`, 및 후행 슬래시(`trailingSlash: true`)는 포함되지 않습니다. +- `query`: `Object` - 객체로 구문 분석된 쿼리 문자열입니다. [dynamic route](/docs/pages/building-your-application/routing/dynamic-routes) 매개변수를 포함합니다. 페이지가 [Server-side Rendering](/docs/pages/building-your-application/data-fetching/get-server-side-props)을 사용하지 않는 경우 prerendering 중에는 빈 객체입니다. 기본값은 `{}` +- `asPath`: `String` - 검색 매개변수를 포함하여 브라우저에 표시되는 경로이며, `trailingSlash` 설정을 존중합니다. `basePath` 및 `locale`은 포함되지 않습니다. +- `isFallback`: `boolean` - 현재 페이지가 [fallback mode](/docs/pages/api-reference/functions/get-static-paths#fallback-true)인지 여부를 나타냅니다. +- `basePath`: `String` - 활성화된 [basePath](/docs/app/api-reference/next-config-js/basePath) (활성화된 경우). +- `locale`: `String` - 활성화된 로케일 (활성화된 경우). +- `locales`: `String[]` - 지원되는 모든 로케일 (활성화된 경우). +- `defaultLocale`: `String` - 현재 기본 로케일 (활성화된 경우). +- `domainLocales`: `Array<{domain, defaultLocale, locales}>` - 구성된 도메인 로케일. +- `isReady`: `boolean` - 라우터 필드가 클라이언트 측에서 업데이트되어 사용 준비가 되었는지 여부. `useEffect` 메서드 내에서만 사용해야 하며 서버에서 조건부 렌더링을 위해 사용해서는 안 됩니다. [automatically statically optimized pages](/docs/pages/building-your-application/rendering/automatic-static-optimization)와 관련된 사용 사례를 참조하세요. +- `isPreview`: `boolean` - 애플리케이션이 현재 [preview mode](/docs/pages/building-your-application/configuring/preview-mode)인지 여부. -> Using the `asPath` field may lead to a mismatch between client and server if the page is rendered using server-side rendering or [automatic static optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization). Avoid using `asPath` until the `isReady` field is `true`. +> `asPath` 필드를 사용하는 경우, 페이지가 서버 사이드 렌더링 또는 [automatic static optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization)를 사용하여 렌더링될 때 클라이언트와 서버 간의 불일치가 발생할 수 있습니다. `isReady` 필드가 `true`가 될 때까지 `asPath` 사용을 피하세요. -The following methods are included inside `router`: +다음 메서드들은 `router` 객체에 포함됩니다: ### router.push -Handles client-side transitions, this method is useful for cases where [`next/link`](/docs/pages/api-reference/components/link) is not enough. +클라이언트 측 전환을 처리합니다. 이 메서드는 [`next/link`](/docs/pages/api-reference/components/link)만으로는 충분하지 않은 경우에 유용합니다. ```js router.push(url, as, options) ``` -- `url`: `UrlObject | String` - The URL to navigate to (see [Node.JS URL module documentation](https://nodejs.org/api/url.html#legacy-urlobject) for `UrlObject` properties). -- `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes. -- `options` - Optional object with the following configuration options: - - `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true` - - [`shallow`](/docs/pages/building-your-application/routing/linking-and-navigating#shallow-routing): Update the path of the current page without rerunning [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props), [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props) or [`getInitialProps`](/docs/pages/api-reference/functions/get-initial-props). Defaults to `false` - - `locale` - Optional string, indicates locale of the new page +- `url`: `UrlObject | String` - 이동할 URL입니다 (`UrlObject` 속성에 대해서는 [Node.JS URL 모듈 문서](https://nodejs.org/api/url.html#legacy-urlobject)를 참조하세요). +- `as`: `UrlObject | String` - 브라우저 URL 표시줄에 표시될 경로를 위한 선택적 데코레이터입니다. Next.js 9.5.3 이전에는 동적 라우트에 사용되었습니다. +- `options` - 다음 구성 옵션이 있는 선택적 객체입니다: + - `scroll` - 선택적 불리언 값으로, 이동 후 페이지 상단으로 스크롤할지 여부를 제어합니다. 기본값은 `true`입니다. + - [`shallow`](/docs/pages/building-your-application/routing/linking-and-navigating#shallow-routing): [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props), [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props) 또는 [`getInitialProps`](/docs/pages/api-reference/functions/get-initial-props)를 다시 실행하지 않고 현재 페이지의 경로를 업데이트합니다. 기본값은 `false`입니다. + - `locale` - 선택적 문자열로, 새 페이지의 로케일을 나타냅니다. -> You don't need to use `router.push` for external URLs. [window.location](https://developer.mozilla.org/docs/Web/API/Window/location) is better suited for those cases. +> 외부 URL에는 `router.push`를 사용할 필요가 없습니다. 이런 경우에는 [window.location](https://developer.mozilla.org/docs/Web/API/Window/location)이 더 적합합니다. -Navigating to `pages/about.js`, which is a predefined route: +미리 정의된 라우트인 `pages/about.js`로 이동하는 예시: ```jsx import { useRouter } from 'next/router' @@ -89,7 +87,7 @@ export default function Page() { } ``` -Navigating `pages/post/[pid].js`, which is a dynamic route: +동적 라우트인 `pages/post/[pid].js`로 이동하는 예시: ```jsx import { useRouter } from 'next/router' @@ -105,13 +103,13 @@ export default function Page() { } ``` -Redirecting the user to `pages/login.js`, useful for pages behind [authentication](/docs/pages/building-your-application/authentication): +사용자를 `pages/login.js`로 리다이렉트하는 예시입니다. [인증](/docs/pages/building-your-application/authentication)이 필요한 페이지에 유용합니다: ```jsx import { useEffect } from 'react' import { useRouter } from 'next/router' -// Here you would fetch and return the user +// 여기서 user를 가져와 반환합니다 const useUser = () => ({ user: null, loading: false }) export default function Page() { @@ -130,7 +128,7 @@ export default function Page() { #### Resetting state after navigation -When navigating to the same page in Next.js, the page's state **will not** be reset by default as React does not unmount unless the parent component has changed. +Next.js에서 동일한 페이지로 이동할 때, React는 부모 컴포넌트가 변경되지 않는 한 언마운트하지 않기 때문에 기본적으로 페이지의 상태는 **초기화되지 않습니다.** ```jsx filename="pages/[slug].js" import Link from 'next/link' @@ -151,11 +149,11 @@ export default function Page(props) { } ``` -In the above example, navigating between `/one` and `/two` **will not** reset the count . The `useState` is maintained between renders because the top-level React component, `Page`, is the same. +위의 예시에서 `/one`과 `/two` 사이를 이동해도 count가 **초기화되지 않습니다**. 최상위 React 컴포넌트인 `Page`가 동일하기 때문에 `useState`는 렌더 간에 유지됩니다. -If you do not want this behavior, you have a couple of options: +이러한 동작을 원하지 않는다면 몇 가지 옵션이 있습니다: -- Manually ensure each state is updated using `useEffect`. In the above example, that could look like: +- `useEffect`를 사용하여 각 상태를 수동으로 업데이트합니다. 위의 예시에서는 다음과 같이 구현할 수 있습니다: ```jsx useEffect(() => { @@ -163,7 +161,7 @@ If you do not want this behavior, you have a couple of options: }, [router.query.slug]) ``` -- Use a React `key` to [tell React to remount the component](https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key). To do this for all pages, you can use a custom app: +- React `key`를 사용하여 [React에게 컴포넌트를 다시 마운트하도록 지시](https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key)합니다. 모든 페이지에 이를 적용하려면 커스텀 앱을 사용할 수 있습니다: ```jsx filename="pages/_app.js" import { useRouter } from 'next/router' @@ -176,7 +174,7 @@ If you do not want this behavior, you have a couple of options: #### With URL object -You can use a URL object in the same way you can use it for [`next/link`](/docs/pages/api-reference/components/link#with-url-object). Works for both the `url` and `as` parameters: +[`next/link`](/docs/pages/api-reference/components/link#with-url-object)와 동일한 방식으로 URL 객체를 사용할 수 있습니다. 이는 `url`과 `as` 매개변수 모두에 적용됩니다: ```jsx import { useRouter } from 'next/router' @@ -202,15 +200,15 @@ export default function ReadMore({ post }) { ### router.replace -Similar to the `replace` prop in [`next/link`](/docs/pages/api-reference/components/link), `router.replace` will prevent adding a new URL entry into the `history` stack. +[`next/link`](/docs/pages/api-reference/components/link)의 `replace` 속성과 유사하게, `router.replace`는 `history` 스택에 새 URL 항목을 추가하지 않습니다. ```js router.replace(url, as, options) ``` -- The API for `router.replace` is exactly the same as the API for [`router.push`](#routerpush). +- `router.replace`의 API는 [`router.push`](#routerpush)의 API와 정확히 동일합니다. -Take a look at the following example: +다음 예시를 살펴보세요: ```jsx import { useRouter } from 'next/router' @@ -228,20 +226,20 @@ export default function Page() { ### router.prefetch -Prefetch pages for faster client-side transitions. This method is only useful for navigations without [`next/link`](/docs/pages/api-reference/components/link), as `next/link` takes care of prefetching pages automatically. +클라이언트 측 전환을 더 빠르게 하기 위해 페이지를 미리 가져옵니다. 이 메서드는 [`next/link`](/docs/pages/api-reference/components/link)를 사용하지 않는 내비게이션에만 유용합니다. `next/link`는 자동으로 페이지를 미리 가져오기 때문입니다. -> This is a production only feature. Next.js doesn't prefetch pages in development. +> 이는 프로덕션 전용 기능입니다. Next.js는 개발 환경에서 페이지를 미리 가져오지 않습니다. ```js router.prefetch(url, as, options) ``` -- `url` - The URL to prefetch, including explicit routes (e.g. `/dashboard`) and dynamic routes (e.g. `/product/[id]`) -- `as` - Optional decorator for `url`. Before Next.js 9.5.3 this was used to prefetch dynamic routes. -- `options` - Optional object with the following allowed fields: - - `locale` - allows providing a different locale from the active one. If `false`, `url` has to include the locale as the active locale won't be used. +- `url` - 미리 가져올 URL입니다. 명시적 라우트(예: `/dashboard`)와 동적 라우트(예: `/product/[id]`)를 포함합니다. +- `as` - `url`에 대한 선택적 데코레이터입니다. Next.js 9.5.3 이전에는 동적 라우트를 미리 가져오는 데 사용되었습니다. +- `options` - 다음 필드를 허용하는 선택적 객체입니다: +- `locale` - 현재 활성화된 로케일과 다른 로케일을 제공할 수 있습니다. `false`인 경우, `url`에 로케일을 포함해야 합니다. 활성 로케일이 사용되지 않기 때문입니다. -Let's say you have a login page, and after a login, you redirect the user to the dashboard. For that case, we can prefetch the dashboard to make a faster transition, like in the following example: +예를 들어, 로그인 페이지가 있고 로그인 후 사용자를 대시보드로 리다이렉트한다고 가정해 봅시다. 이 경우, 다음 예시와 같이 대시보드를 미리 가져와 더 빠른 전환을 할 수 있습니다: ```jsx import { useCallback, useEffect } from 'react' @@ -259,13 +257,13 @@ export default function Login() { /* Form data */ }), }).then((res) => { - // Do a fast client-side transition to the already prefetched dashboard page + // 이미 미리 가져온 대시보드 페이지로 빠른 클라이언트 측 전환을 수행합니다 if (res.ok) router.push('/dashboard') }) }, []) useEffect(() => { - // Prefetch the dashboard page + // 대시보드 페이지를 미리 가져옵니다 router.prefetch('/dashboard') }, [router]) @@ -280,20 +278,20 @@ export default function Login() { ### router.beforePopState -In some cases (for example, if using a [Custom Server](/docs/pages/building-your-application/configuring/custom-server)), you may wish to listen to [popstate](https://developer.mozilla.org/docs/Web/Events/popstate) and do something before the router acts on it. +일부 경우([Custom Server](/docs/pages/building-your-application/configuring/custom-server)를 사용하는 경우 등)에는 [popstate](https://developer.mozilla.org/docs/Web/Events/popstate)를 감지하고 라우터가 이를 처리하기 전에 무언가를 수행하고 싶을 수 있습니다. ```js router.beforePopState(cb) ``` -- `cb` - The function to run on incoming `popstate` events. The function receives the state of the event as an object with the following props: - - `url`: `String` - the route for the new state. This is usually the name of a `page` - - `as`: `String` - the url that will be shown in the browser - - `options`: `Object` - Additional options sent by [router.push](#routerpush) +- `cb` - 들어오는 `popstate` 이벤트에 대해 실행할 함수입니다. 이 함수는 다음 속성을 가진 객체로 이벤트의 상태를 받습니다: +- `url`: `String` - 새로운 상태에 대한 라우트입니다. 보통 `page`의 이름입니다. +- `as`: `String` - 브라우저에 표시될 URL입니다. +- `options`: `Object` - [router.push](#routerpush)에 의해 전송된 추가 옵션입니다. -If `cb` returns `false`, the Next.js router will not handle `popstate`, and you'll be responsible for handling it in that case. See [Disabling file-system routing](/docs/pages/building-your-application/configuring/custom-server#disabling-file-system-routing). +`cb`가 `false`를 반환하면 Next.js 라우터는 `popstate`를 처리하지 않으며, 그 경우 직접 처리해야 합니다. [파일 시스템 라우팅 비활성화하기](/docs/pages/building-your-application/configuring/custom-server#disabling-file-system-routing)를 참조하세요. -You could use `beforePopState` to manipulate the request, or force a SSR refresh, as in the following example: +`beforePopState`를 사용하여 요청을 조작하거나 SSR 새로고침을 강제할 수 있습니다. 다음 예시를 참조하세요: ```jsx import { useEffect } from 'react' @@ -304,9 +302,9 @@ export default function Page() { useEffect(() => { router.beforePopState(({ url, as, options }) => { - // I only want to allow these two routes! + // 이 두 라우트만 허용하고 싶습니다! if (as !== '/' && as !== '/other') { - // Have SSR render bad routes as a 404. + // SSR이 잘못된 라우트를 404로 렌더링하도록 합니다. window.location.href = as return false } @@ -321,7 +319,7 @@ export default function Page() { ### router.back -Navigate back in history. Equivalent to clicking the browser’s back button. It executes `window.history.back()`. +히스토리에서 뒤로 이동합니다. 브라우저의 뒤로 가기 버튼을 클릭하는 것과 동일합니다. `window.history.back()`을 실행합니다. ```jsx import { useRouter } from 'next/router' @@ -339,7 +337,7 @@ export default function Page() { ### router.reload -Reload the current URL. Equivalent to clicking the browser’s refresh button. It executes `window.location.reload()`. +현재 URL을 새로고침합니다. 브라우저의 새로고침 버튼을 클릭하는 것과 동일합니다. `window.location.reload()`를 실행합니다. ```jsx import { useRouter } from 'next/router' @@ -357,19 +355,19 @@ export default function Page() { ### router.events -You can listen to different events happening inside the Next.js Router. Here's a list of supported events: +Next.js 라우터 내에서 발생하는 다양한 이벤트를 감지할 수 있습니다. 지원되는 이벤트 목록은 다음과 같습니다: -- `routeChangeStart(url, { shallow })` - Fires when a route starts to change -- `routeChangeComplete(url, { shallow })` - Fires when a route changed completely -- `routeChangeError(err, url, { shallow })` - Fires when there's an error when changing routes, or a route load is cancelled - - `err.cancelled` - Indicates if the navigation was cancelled -- `beforeHistoryChange(url, { shallow })` - Fires before changing the browser's history -- `hashChangeStart(url, { shallow })` - Fires when the hash will change but not the page -- `hashChangeComplete(url, { shallow })` - Fires when the hash has changed but not the page +- `routeChangeStart(url, { shallow })` - 라우트 변경이 시작될 때 발생합니다. +- `routeChangeComplete(url, { shallow })` - 라우트 변경이 완전히 완료되었을 때 발생합니다. +- `routeChangeError(err, url, { shallow })` - 라우트 변경 중 오류가 발생하거나 라우트 로드가 취소되었을 때 발생합니다. +- `err.cancelled` - 내비게이션이 취소되었는지를 나타냅니다. +- `beforeHistoryChange(url, { shallow })` - 브라우저의 히스토리를 변경하기 전에 발생합니다. +- `hashChangeStart(url, { shallow })` - 해시가 변경되지만 페이지는 변경되지 않을 때 발생합니다. +- `hashChangeComplete(url, { shallow })` - 해시가 변경되었지만 페이지는 변경되지 않았을 때 발생합니다. -> **Good to know**: Here `url` is the URL shown in the browser, including the [`basePath`](/docs/app/api-reference/next-config-js/basePath). +> **알아두면 좋은 점**: 여기서 `url`은 [`basePath`](/docs/app/api-reference/next-config-js/basePath)를 포함한 브라우저에 표시되는 URL입니다. -For example, to listen to the router event `routeChangeStart`, open or create `pages/_app.js` and subscribe to the event, like so: +예를 들어, 라우터 이벤트 `routeChangeStart`를 감지하려면 `pages/_app.js`를 열거나 생성하고 다음과 같이 이벤트를 구독하세요: ```jsx import { useEffect } from 'react' @@ -389,8 +387,8 @@ export default function MyApp({ Component, pageProps }) { router.events.on('routeChangeStart', handleRouteChange) - // If the component is unmounted, unsubscribe - // from the event with the `off` method: + // 컴포넌트가 언마운트되면 + // `off` 메서드로 이벤트 구독을 해제합니다: return () => { router.events.off('routeChangeStart', handleRouteChange) } @@ -400,11 +398,11 @@ export default function MyApp({ Component, pageProps }) { } ``` -> We use a [Custom App](/docs/pages/building-your-application/routing/custom-app) (`pages/_app.js`) for this example to subscribe to the event because it's not unmounted on page navigations, but you can subscribe to router events on any component in your application. +> 이 예제에서는 [Custom App](/docs/pages/building-your-application/routing/custom-app) (`pages/_app.js`)을 사용하여 이벤트를 구독합니다. 이는 페이지 내비게이션 시 언마운트되지 않기 때문입니다. 하지만 애플리케이션의 어떤 컴포넌트에서도 라우터 이벤트를 구독할 수 있습니다. -Router events should be registered when a component mounts ([useEffect](https://react.dev/reference/react/useEffect) or [componentDidMount](https://react.dev/reference/react/Component#componentdidmount) / [componentWillUnmount](https://react.dev/reference/react/Component#componentwillunmount)) or imperatively when an event happens. +라우터 이벤트는 컴포넌트가 마운트될 때([useEffect](https://react.dev/reference/react/useEffect) 또는 [componentDidMount](https://react.dev/reference/react/Component#componentdidmount) / [componentWillUnmount](https://react.dev/reference/react/Component#componentwillunmount))나 이벤트가 발생하는 시점에 직접 등록해야 합니다. -If a route load is cancelled (for example, by clicking two links rapidly in succession), `routeChangeError` will fire. And the passed `err` will contain a `cancelled` property set to `true`, as in the following example: +라우트 로드가 취소되면(예: 두 개의 링크를 연속해서 빠르게 클릭한 경우) `routeChangeError`가 발생합니다. 그리고 전달된 `err`는 다음 예시와 같이 `cancelled` 속성이 `true`로 설정됩니다: ```jsx import { useEffect } from 'react' @@ -422,8 +420,8 @@ export default function MyApp({ Component, pageProps }) { router.events.on('routeChangeError', handleRouteChangeError) - // If the component is unmounted, unsubscribe - // from the event with the `off` method: + // 컴포넌트가 언마운트되면 + // `off` 메서드로 이벤트 구독을 해제합니다: return () => { router.events.off('routeChangeError', handleRouteChangeError) } @@ -435,11 +433,11 @@ export default function MyApp({ Component, pageProps }) { ## Potential ESLint errors -Certain methods accessible on the `router` object return a Promise. If you have the ESLint rule, [no-floating-promises](https://typescript-eslint.io/rules/no-floating-promises) enabled, consider disabling it either globally, or for the affected line. +`router` 객체에서 접근 가능한 특정 메서드들은 Promise를 반환합니다. [no-floating-promises](https://typescript-eslint.io/rules/no-floating-promises) ESLint 규칙을 사용 중이라면, 전역적으로 또는 해당 라인에 대해 이 규칙을 비활성화하는 것을 고려해보세요. -If your application needs this rule, you should either `void` the promise – or use an `async` function, `await` the Promise, then void the function call. **This is not applicable when the method is called from inside an `onClick` handler**. +애플리케이션에 이 규칙이 필요한 경우, Promise를 `void` 처리하거나 `async` 함수를 사용하여 Promise를 `await`한 후 함수 호출을 void 처리해야 합니다. **이는 `onClick` 핸들러 내부에서 메서드가 호출될 때는 적용되지 않습니다**. -The affected methods are: +영향을 받는 메서드들은 다음과 같습니다: - `router.push` - `router.replace` @@ -451,7 +449,7 @@ The affected methods are: import { useEffect } from 'react' import { useRouter } from 'next/router' -// Here you would fetch and return the user +// 여기서 user를 가져와 반환합니다 const useUser = () => ({ user: null, loading: false }) export default function Page() { @@ -459,15 +457,15 @@ export default function Page() { const router = useRouter() useEffect(() => { - // disable the linting on the next line - This is the cleanest solution + // 다음 줄의 린팅을 비활성화합니다 - 가장 깔끔한 해결책입니다 // eslint-disable-next-line no-floating-promises router.push('/login') - // void the Promise returned by router.push + // router.push가 반환하는 Promise를 void 처리합니다 if (!(user || loading)) { void router.push('/login') } - // or use an async function, await the Promise, then void the function call + // 또는 async 함수를 사용하고, Promise를 await한 다음 함수 호출을 void 처리합니다 async function handleRouteChange() { if (!(user || loading)) { await router.push('/login') @@ -482,7 +480,7 @@ export default function Page() { ## withRouter -If [`useRouter`](#router-object) is not the best fit for you, `withRouter` can also add the same [`router` object](#router-object) to any component. +[`useRouter`](#router-object)가 적합하지 않은 경우, `withRouter`를 사용하여 동일한 [`router` object](#router-object)를 어떤 컴포넌트에도 추가할 수 있습니다. ### Usage @@ -498,7 +496,7 @@ export default withRouter(Page) ### TypeScript -To use class components with `withRouter`, the component needs to accept a router prop: +`withRouter`를 클래스 컴포넌트와 함께 사용하려면, 컴포넌트가 router prop을 허용해야 합니다: ```tsx import React from 'react' diff --git a/pages/docs/pages/building-your-application/configuring/amp.mdx b/pages/docs/pages/building-your-application/configuring/amp.mdx index 0841939..88d3355 100644 --- a/pages/docs/pages/building-your-application/configuring/amp.mdx +++ b/pages/docs/pages/building-your-application/configuring/amp.mdx @@ -3,32 +3,30 @@ title: AMP description: With minimal config, and without leaving React, you can start adding AMP and improve the performance and speed of your pages. --- -{/* TODO: 번역이 필요합니다. */} - # AMP
    Examples - + - [AMP](https://github.com/vercel/next.js/tree/canary/examples/amp)
    -With Next.js you can turn any React page into an AMP page, with minimal config, and without leaving React. +Next.js를 사용하면 최소한의 설정만으로 React 환경을 벗어나지 않고도 모든 React 페이지를 AMP 페이지로 쉽게 변환할 수 있습니다. -You can read more about AMP in the official [amp.dev](https://amp.dev/) site. +AMP에 대해 자세히 알아보려면 공식 [amp.dev](https://amp.dev) 사이트를 방문해 보세요. ## Enabling AMP -To enable AMP support for a page, and to learn more about the different AMP configs, read the [API documentation for `next/amp`](/docs/pages/building-your-application/configuring/amp). +AMP를 페이지에서 활성화하고 다양한 AMP 설정에 대해 더 알아보려면 [`next/amp`의 API 문서](/docs/app/building-your-application/configuring/amp)를 읽어보세요. ## Caveats -- Only CSS-in-JS is supported. [CSS Modules](/docs/pages/building-your-application/styling) aren't supported by AMP pages at the moment. You can [contribute CSS Modules support to Next.js](https://github.com/vercel/next.js/issues/10549). +- 현재 AMP 페이지에서는 CSS-in-JS만 지원되며, [CSS Modules](/docs/app/building-your-application/styling)는 지원되지 않습니다. [Next.js에 CSS Modules 지원을 직접 기여하실 수 있습니다.](https://github.com/vercel/next.js/issues/10549) ## Adding AMP Components -The AMP community provides [many components](https://amp.dev/documentation/components/) to make AMP pages more interactive. Next.js will automatically import all components used on a page and there is no need to manually import AMP component scripts: +AMP 커뮤니티는 AMP 페이지를 더욱 인터랙티브하게 만들기 위해 [다양한 컴포넌트](https://amp.dev/documentation/components/)를 제공합니다. Next.js는 페이지에서 사용되는 모든 AMP 컴포넌트를 자동으로 가져오기 때문에 AMP 컴포넌트 스크립트를 수동으로 가져올 필요가 없습니다: ```jsx export const config = { amp: true } @@ -54,9 +52,9 @@ function MyAmpPage() { export default MyAmpPage ``` -The above example uses the [`amp-timeago`](https://amp.dev/documentation/components/amp-timeago/?format=websites) component. +위 예제는 [`amp-timeago`](https://amp.dev/documentation/components/amp-timeago/?format=websites) 컴포넌트를 사용합니다. -By default, the latest version of a component is always imported. If you want to customize the version, you can use `next/head`, as in the following example: +기본적으로 항상 최신 버전의 컴포넌트를 가져옵니다(import). 버전을 커스터마이징하여 사용하려면 `next/head`를 사용해 다음과 같이 사용할 수 있습니다: ```jsx import Head from 'next/head' @@ -95,13 +93,13 @@ export default MyAmpPage ## AMP Validation -AMP pages are automatically validated with [amphtml-validator](https://www.npmjs.com/package/amphtml-validator) during development. Errors and warnings will appear in the terminal where you started Next.js. +AMP 페이지는 개발 중에 [amphtml-validator](https://www.npmjs.com/package/amphtml-validator)를 통해 자동으로 검증됩니다. 오류와 경고는 터미널에 출력됩니다. -Pages are also validated during [Static HTML export](/docs/pages/building-your-application/deploying/static-exports) and any warnings / errors will be printed to the terminal. Any AMP errors will cause the export to exit with status code `1` because the export is not valid AMP. +[정적 HTML 내보내기](/docs/app/building-your-application/deploying/static-exports) 중에도 페이지가 검증되며, 경고나 오류는 터미널에 출력됩니다. AMP 오류가 있을 경우, 내보내기(export)는 상태 코드 `1`로 종료되며, 이는 내보내기(export)가 유효한 AMP가 아니기 때문입니다. ### Custom Validators -You can set up custom AMP validator in `next.config.js` as shown below: +다음과 같이 `next.config.js`에서 커스텀 AMP validator를 설정할 수 있습니다: ```js module.exports = { @@ -113,7 +111,7 @@ module.exports = { ### Skip AMP Validation -To turn off AMP validation add the following code to `next.config.js` +AMP 검증을 비활성화하려면 next.config.js에 다음 코드를 추가하세요: ```js experimental: { @@ -125,36 +123,35 @@ experimental: { ### AMP in Static HTML Export -When using [Static HTML export](/docs/pages/building-your-application/deploying/static-exports) statically prerender pages, Next.js will detect if the page supports AMP and change the exporting behavior based on that. - -For example, the hybrid AMP page `pages/about.js` would output: +[정적 HTML 내보내기 기능을](/docs/app/building-your-application/deploying/static-exports) 사용하여 페이지를 정적으로 사전 렌더링(prerender)할 때, Next.js는 페이지가 AMP를 지원하는지 감지하고 이에 따라 내보내기(export) 동작을 변경합니다. +예를 들어, 하이브리드 AMP 페이지 `pages/about.js`는 다음과 같이 출력됩니다: -- `out/about.html` - HTML page with client-side React runtime -- `out/about.amp.html` - AMP page +- `out/about.html` - 클라이언트 사이드에서 실행되는 HTML 페이지 +- `out/about.amp.html-AMP` - AMP 페이지 -And if `pages/about.js` is an AMP-only page, then it would output: +그리고 만약 `pages/about.js`가 AMP-only 페이지일 경우: -- `out/about.html` - Optimized AMP page +- `out/about.html` - 최적화된 AMP 페이지 -Next.js will automatically insert a link to the AMP version of your page in the HTML version, so you don't have to, like so: +Next.js는 HTML 버전에 페이지의 AMP 버전 링크를 자동으로 삽입하므로 이를 직접 추가할 필요가 없습니다. 예를 들어: ```jsx ``` -And the AMP version of your page will include a link to the HTML page: +그리고 페이지의 AMP 버전에는 HTML 페이지에 대한 링크가 다음과 같이 포함됩니다: ```jsx ``` -When [`trailingSlash`](/docs/pages/api-reference/next-config-js/trailingSlash) is enabled the exported pages for `pages/about.js` would be: +[`trailingSlash`](/docs/app/api-reference/next-config-js/trailingSlash)가 활성화된 경우, 내보내지는 `pages/about.js` 페이지의 결과는 다음과 같습니다: -- `out/about/index.html` - HTML page -- `out/about.amp/index.html` - AMP page +- `out/about/index.html` - HTML 페이지 +- `out/about.amp/index.html` - AMP 페이지 ## TypeScript -AMP currently doesn't have built-in types for TypeScript, but it's in their roadmap ([#13791](https://github.com/ampproject/amphtml/issues/13791)). +현재 AMP는 TypeScript를 위한 내장 타입을 제공하지 않지만, 이는 로드맵([#13791](https://github.com/ampproject/amphtml/issues/13791))에 포함되어 있습니다. -As a workaround you can manually create a file called `amp.d.ts` inside your project and add these [custom types](https://stackoverflow.com/a/50601125). +대안으로, 프로젝트 내에 `amp.d.ts`라는 파일을 수동으로 생성하고 다음과 같은 [사용자 정의 타입](https://stackoverflow.com/questions/50585952/property-amp-img-does-not-exist-on-type-jsx-intrinsicelements/50601125#50601125)을 추가할 수 있습니다. diff --git a/pages/docs/pages/building-your-application/configuring/draft-mode.mdx b/pages/docs/pages/building-your-application/configuring/draft-mode.mdx index 1c97902..c743673 100644 --- a/pages/docs/pages/building-your-application/configuring/draft-mode.mdx +++ b/pages/docs/pages/building-your-application/configuring/draft-mode.mdx @@ -3,23 +3,21 @@ title: Draft Mode description: Next.js has draft mode to toggle between static and dynamic pages. You can learn how it works with Pages Router. --- -{/* TODO: 번역이 필요합니다. */} - # Draft Mode -In the [Pages documentation](/docs/pages/building-your-application/routing/pages-and-layouts) and the [Data Fetching documentation](/docs/pages/building-your-application/data-fetching), we talked about how to pre-render a page at build time (**Static Generation**) using `getStaticProps` and `getStaticPaths`. +[Pages 문서](/docs/pages/building-your-application/routing/pages-and-layouts) 및 [Data Fetching 문서](/docs/pages/building-your-application/data-fetching)에서 `getStaticProps`와 `getStaticPaths`를 사용하여 빌드 타임에 페이지를 사전 렌더링(**정적 생성**)하는 방법에 대해 이야기했습니다. -Static Generation is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to view the draft immediately on your page. You’d want Next.js to render these pages at **request time** instead of build time and fetch the draft content instead of the published content. You’d want Next.js to bypass Static Generation only for this specific case. +정적 생성은 페이지가 헤드리스 CMS에서 데이터를 가져올 때 유용합니다. 하지만 헤드리스 CMS에서 초안을 작성하고 페이지에서 바로 보는 것을 원할 때는 이상적이지 않습니다. 이러한 경우 Next.js가 이 페이지들을 빌드 타임이 아닌 **요청 타임**에 렌더링하고 게시된 컨텐츠 대신 초안 컨텐츠를 가져오도록 하고 싶을 것입니다. 이와 같이 Next.js가 특정 경우에 정적 생성을 우회하기를 원할 수 있습니다. -Next.js has a feature called **Draft Mode** which solves this problem. Here are instructions on how to use it. +Next.js에는 이러한 문제를 해결하는 **Draft Mode**라는 기능을 제공합니다. 사용 방법은 다음과 같습니다. ## Step 1: Create and access the API route -> Take a look at the [API Routes documentation](/docs/pages/building-your-application/routing/api-routes) first if you’re not familiar with Next.js API Routes. +> Next.js API Routes를 잘 모르는 경우 [API Routes 문서](/docs/pages/building-your-application/routing/api-routes)을 먼저 참조하십시오. -First, create the **API route**. It can have any name - e.g. `pages/api/draft.ts` +먼저 **초안 API route**를 만듭니다. 이름은 자유롭게 설정할 수 있습니다 - 예: `pages/api/draft.js` -In this API route, you need to call `setDraftMode` on the response object. +이 API route에서 응답 객체에 `setDraftMode`를 호출해야 합니다. ```js export default function handler(req, res) { @@ -29,100 +27,99 @@ export default function handler(req, res) { } ``` -This will set a **cookie** to enable draft mode. Subsequent requests containing this cookie will trigger **Draft Mode** changing the behavior for statically generated pages (more on this later). +이렇게 하면 draft 모드를 활성화하는 **쿠키**가 설정됩니다. 이러한 쿠키를 포함한 후속 요청은 **Draft Mode**를 트리거하여 정적으로 생성된 페이지의 동작을 변경합니다(이후에 더 설명함). -You can test this manually by creating an API route like below and accessing it from your browser manually: +브라우저에서 직접 액세스하여 수동으로 테스트할 수 있도록 다음과 같은 API route를 만들고 액세스해보세요: ```ts filename="pages/api/draft.ts" -// simple example for testing it manually from your browser. +// 브라우저에서 수동으로 테스트하기 위한 간단한 예제입니다. export default function handler(req, res) { res.setDraftMode({ enable: true }) res.end('Draft mode is enabled') } ``` -If you open your browser’s developer tools and visit `/api/draft`, you’ll notice a `Set-Cookie` response header with a cookie named `__prerender_bypass`. +브라우저의 개발자 도구를 열고 `/api/draft`를 확인하면 `__prerender_bypass`라는 이름의 쿠키가 포함된 `Set-Cookie` 응답 헤더를 확인할 수 있습니다. ### Securely accessing it from your Headless CMS -In practice, you’d want to call this API route _securely_ from your headless CMS. The specific steps will vary depending on which headless CMS you’re using, but here are some common steps you could take. +실제로는 헤드리스 CMS에서 이 라우트 핸들러를 _보안_ 방식으로 호출하고 싶을 것입니다. 사용 중인 헤드리스 CMS에 따라 구체적인 단계는 다를 수 있지만, 다음과 같은 일반적인 단계를 따를 수 있습니다. -These steps assume that the headless CMS you’re using supports setting **custom draft URLs**. If it doesn’t, you can still use this method to secure your draft URLs, but you’ll need to construct and access the draft URL manually. +이 단계는 사용 중인 헤드리스 CMS가 **사용자 정의 초안 URL** 설정을 지원한다고 가정합니다. 지원하지 않는 경우에도 이 방법을 사용하여 초안 URL을 보호할 수 있지만, 초안 URL을 수동으로 구성하고 접근해야 합니다. -**First**, you should create a **secret token string** using a token generator of your choice. This secret will only be known by your Next.js app and your headless CMS. This secret prevents people who don’t have access to your CMS from accessing draft URLs. +**먼저**, 원하는 토큰 생성기를 사용하여 **시크릿 토큰 문자열**을 생성해야 합니다. 이 시크릿은 Next.js 앱과 헤드리스 CMS만 알고 있어야 합니다. 이 시크릿은 CMS에 액세스할 수 없는 사람들이 초안 URL에 접근하는 것을 방지합니다. -**Second**, if your headless CMS supports setting custom draft URLs, specify the following as the draft URL. This assumes that your draft API route is located at `pages/api/draft.ts`. +**두 번째**, 헤드리스 CMS가 사용자 정의 초안 URL 설정을 지원하는 경우, 다음을 초안 URL로 지정합니다. 이는 초안 API route가 `pages/api/draft.js`에 위치한다고 가정합니다. ```bash filename="Terminal" https:///api/draft?secret=&slug= ``` -- `` should be your deployment domain. -- `` should be replaced with the secret token you generated. -- `` should be the path for the page that you want to view. If you want to view `/posts/foo`, then you should use `&slug=/posts/foo`. +- ``는 배포 도메인이어야 합니다. +- ``은 생성한 시크릿 토큰으로 교체해야 합니다. +- `` 는 보려고 하는 페이지의 경로여야 합니다. `/posts/foo`를 보고자 한다면 `&slug=/posts/foo`를 사용해야 합니다. -Your headless CMS might allow you to include a variable in the draft URL so that `` can be set dynamically based on the CMS’s data like so: `&slug=/posts/{entry.fields.slug}` +사용중인 헤드리스 CMS가 변수 삽입을 지원하는 경우 ``를 CMS 데이터에 따라 동적으로 설정할 수 있습니다: `&slug=/posts/{entry.fields.slug}` -**Finally**, in the draft API route: +**마지막으로**, 초안 API route에서: -- Check that the secret matches and that the `slug` parameter exists (if not, the request should fail). -- -- Call `res.setDraftMode`. -- Then redirect the browser to the path specified by `slug`. (The following example uses a [307 redirect](https://developer.mozilla.org/docs/Web/HTTP/Status/307)). +- 시크릿이 일치하고 `slug` 매개변수가 존재하는지 확인합니다(존재하지 않으면 요청이 실패해야 합니다). +- `res.setDraftMode`를 호출합니다. +- 그런 다음 브라우저를 `slug`로 지정된 경로로 리디렉션합니다(다음 예제에서는 [307 redirect](https://developer.mozilla.org/docs/Web/HTTP/Status/307)을 사용합니다). ```js export default async (req, res) => { - // Check the secret and next parameters - // This secret should only be known to this API route and the CMS + // 시크릿과 다음 매개변수를 확인합니다. + // 이 시크릿은 이 API route와 CMS만 알고 있어야 합니다. if (req.query.secret !== 'MY_SECRET_TOKEN' || !req.query.slug) { return res.status(401).json({ message: 'Invalid token' }) } - // Fetch the headless CMS to check if the provided `slug` exists - // getPostBySlug would implement the required fetching logic to the headless CMS + // 제공된 `slug`가 존재하는지 확인하기 위해 헤드리스 CMS를 가져옵니다. + // getPostBySlug는 헤드리스 CMS에 필요한 fetching 로직을 구현합니다. const post = await getPostBySlug(req.query.slug) - // If the slug doesn't exist prevent draft mode from being enabled + // slug가 존재하지 않으면 Draft Mode가 활성화되지 않도록 합니다. if (!post) { return res.status(401).json({ message: 'Invalid slug' }) } - // Enable Draft Mode by setting the cookie + // 쿠키를 설정하여 Draft Mode를 활성화합니다. res.setDraftMode({ enable: true }) - // Redirect to the path from the fetched post - // We don't redirect to req.query.slug as that might lead to open redirect vulnerabilities + // 가져온 게시물의 경로로 리디렉션합니다. + // req.query.slug로 리디렉션하지 않는 이유는 open redirect 취약점이 발생할 수 있기 때문입니다. res.redirect(post.slug) } ``` -If it succeeds, then the browser will be redirected to the path you want to view with the draft mode cookie. +성공하면 브라우저는 설정된 draft mode 쿠키와 함께 보고자 하는 경로로 리디렉션됩니다. ## Step 2: Update `getStaticProps` -The next step is to update `getStaticProps` to support draft mode. +다음 단계는 `getStaticProps`를 업데이트하여 draft mode를 지원하는 것입니다. -If you request a page which has `getStaticProps` with the cookie set (via `res.setDraftMode`), then `getStaticProps` will be called at **request time** (instead of at build time). +`res.setDraftMode`를 통해 쿠키가 설정된 페이지를 요청하면 `getStaticProps`가 **빌드 타임**이 아닌 **요청 타임**에 호출됩니다. -Furthermore, it will be called with a `context` object where `context.draftMode` will be `true`. +또한, `context.draftMode`가 `true`인 `context` 객체와 함께 호출됩니다. ```js export async function getStaticProps(context) { if (context.draftMode) { - // dynamic data + // 동적 데이터 } } ``` -We used `res.setDraftMode` in the draft API route, so `context.draftMode` will be `true`. +우리는 초안 API route에서 `res.setDraftMode`를 사용했으므로 `context.draftMode`는 `true`가 됩니다. -If you’re also using `getStaticPaths`, then `context.params` will also be available. +`getStaticPaths`를 사용하는 경우, `context.params`도 사용할 수 있습니다. ### Fetch draft data -You can update `getStaticProps` to fetch different data based on `context.draftMode`. +`getStaticProps`를 업데이트하여 `context.draftMode`에 따라 다른 데이터를 가져올 수 있습니다. -For example, your headless CMS might have a different API endpoint for draft posts. If so, you can modify the API endpoint URL like below: +예를 들어, 헤드리스 CMS가 초안 게시물에 대해 다른 API 엔드포인트를 가지고 있는 경우, 아래와 같이 API 엔드포인트 URL을 수정할 수 있습니다: ```js export async function getStaticProps(context) { @@ -134,9 +131,9 @@ export async function getStaticProps(context) { } ``` -That’s it! If you access the draft API route (with `secret` and `slug`) from your headless CMS or manually, you should now be able to see the draft content. And if you update your draft without publishing, you should be able to view the draft. +이제 초안 API route(`시크릿` 및 `slug` 포함)를 헤드리스 CMS 또는 수동으로 접근하면 초안 컨텐츠를 볼 수 있어야 합니다. 초안을 게시하지 않고 업데이트하더라도 초안을 볼 수 있어야 합니다. -Set this as the draft URL on your headless CMS or access manually, and you should be able to see the draft. +헤드리스 CMS에 이를 초안 URL로 설정하거나 수동으로 접근하면 초안을 볼 수 있습니다. ```bash filename="Terminal" https:///api/draft?secret=&slug= @@ -146,9 +143,9 @@ https:///api/draft?secret=&slug= ### Clear the Draft Mode cookie -By default, the Draft Mode session ends when the browser is closed. +기본적으로 초안 모드 세션은 브라우저를 닫으면 종료됩니다. -To clear the Draft Mode cookie manually, create an API route that calls `setDraftMode({ enable: false })`: +초안 모드 쿠키를 수동으로 지우려면 `setDraftMode({ enable: false })`를 호출하는 API route를 만듭니다: ```ts filename="pages/api/disable-draft.ts" export default function handler(req, res) { @@ -156,30 +153,29 @@ export default function handler(req, res) { } ``` -Then, send a request to `/api/disable-draft` to invoke the API Route. If calling this route using [`next/link`](/docs/pages/api-reference/components/link), you must pass `prefetch={false}` to prevent accidentally deleting the cookie on prefetch. +그런 다음 `/api/disable-draft`에 요청을 보내 API Route를 호출합니다. [`next/link`](/docs/pages/api-reference/components/link)를 사용하여 이 라우트를 호출하는 경우, 쿠키가 prefech 중에 실수로 삭제되지 않도록 `prefetch={false}`를 전달해야 합니다. ### Works with `getServerSideProps` -Draft Mode works with `getServerSideProps`, and is available as a `draftMode` key in the [`context`](/docs/pages/api-reference/functions/get-server-side-props#context-parameter) object. +Draft mode는 `getServerSideProps`와 함께 작동하며, `context` 객체에 `draftMode` 키로 사용할 수 있습니다. -> **Good to know**: You shouldn't set the `Cache-Control` header when using Draft Mode because it cannot be bypassed. Instead, we recommend using [ISR](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration). +> **참고**: Draft Mode를 사용할 때 `Cache-Control` 헤더를 설정하면 우회할 수 없으므로 설정하지 않아야 합니다. 대신, [ISR](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)을 사용하는 것을 추천합니다. ### Works with API Routes -API Routes will have access to `draftMode` on the request object. For example: +API Routes는 요청 객체에서 `draftMode`에 접근할 수 있습니다. 예를 들어: ```js export default function myApiRoute(req, res) { if (req.draftMode) { - // get draft data + // 초안 데이터를 가져옵니다. } } ``` ### Unique per `next build` -A new bypass cookie value will be generated each time you run `next build`. - -This ensures that the bypass cookie can’t be guessed. +`next build`를 실행할 때마다 새로운 우회 쿠키 값이 생성됩니다. +이를 통해서 우회 쿠키를 추측할 수 없도록 합니다. -> **Good to know**: To test Draft Mode locally over HTTP, your browser will need to allow third-party cookies and local storage access. +> **참고**: 로컬에서 HTTP를 통해 Draft Mode를 테스트하려면 브라우저에서 서드 파티 쿠키와 로컬 스토리지 액세스를 허용해야 합니다. diff --git a/pages/docs/pages/building-your-application/routing/api-routes.mdx b/pages/docs/pages/building-your-application/routing/api-routes.mdx index 6359926..d328e01 100644 --- a/pages/docs/pages/building-your-application/routing/api-routes.mdx +++ b/pages/docs/pages/building-your-application/routing/api-routes.mdx @@ -3,8 +3,6 @@ title: API Routes description: Next.js supports API Routes, which allow you to build your API without leaving your Next.js app. Learn how it works here. --- -{/* TODO: 번역이 필요합니다. */} - # API Routes
    @@ -18,13 +16,13 @@ description: Next.js supports API Routes, which allow you to build your API with
    -> **Good to know**: If you are using the App Router, you can use [Server Components](/docs/app/building-your-application/rendering/server-components) or [Route Handlers](/docs/app/building-your-application/routing/route-handlers) instead of API Routes. +> **Good to know** : App Router를 사용하는 경우, API Routes 대신 [Server Components](/docs/app/building-your-application/rendering/server-components) 또는 [Route Handlers](/docs/app/building-your-application/routing/route-handlers) 를 사용할 수 있습니다. -API routes provide a solution to build a **public API** with Next.js. +API routes는 Next.js로 **공용 API** 를 구축할 수 있는 솔루션을 제공합니다. -Any file inside the folder `pages/api` is mapped to `/api/*` and will be treated as an API endpoint instead of a `page`. They are server-side only bundles and won't increase your client-side bundle size. +`pages/api` 폴더 내부의 모든 파일은 `/api/*`로 매핑되어 `page` 대신 API 엔드포인트로 처리됩니다. 이러한 파일들은 서버 사이드 번들로만 존재하며, 클라이언트 사이드 번들 크기를 증가시키지 않습니다. -For example, the following API route returns a JSON response with a status code of `200`: +예를 들어, 다음 API 라우트는 상태 코드 `200`과 함께 JSON 응답을 반환합니다: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -49,10 +47,10 @@ export default function handler(req, res) { > **Good to know**: > -> - API Routes [do not specify CORS headers](https://developer.mozilla.org/docs/Web/HTTP/CORS), meaning they are **same-origin only** by default. You can customize such behavior by wrapping the request handler with the [CORS request helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors). +> - API Routes는 기본적으로 **동일 출처** 만 허용하며, [CORS 헤더를 지정하지 않습니다](https://developer.mozilla.org/docs/Web/HTTP/CORS) . 이러한 동작은 [CORS 요청 도우미](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors) 로 요청 핸들러를 감싸서 사용자 정의할 수 있습니다. -- API Routes can't be used with [static exports](/docs/pages/building-your-application/deploying/static-exports). However, [Route Handlers](/docs/app/building-your-application/routing/route-handlers) in the App Router can. - > - API Routes will be affected by [`pageExtensions` configuration](/docs/pages/api-reference/next-config-js/pageExtensions) in `next.config.js`. +- API Routes는 [정적 내보내기](/docs/pages/building-your-application/deploying/static-exports) 와 함께 사용할 수 없습니다. 그러나 App Router의 [Route Handlers](/docs/app/building-your-application/routing/route-handlers) 를 사용할 수 있습니다. + > - API Routes는 `next.config.js`의 [pageExtensions 설정](/docs/pages/api-reference/next-config-js/pageExtensions) 의 영향을 받습니다. ## Parameters @@ -62,21 +60,21 @@ export default function handler(req: NextApiRequest, res: NextApiResponse) { } ``` -- `req`: An instance of [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage) -- `res`: An instance of [http.ServerResponse](https://nodejs.org/api/http.html#class-httpserverresponse) +- `req`: [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage) 인스턴스 +- `res`: [http.ServerResponse](https://nodejs.org/api/http.html#class-httpserverresponse) 인스턴스 ## HTTP Methods -To handle different HTTP methods in an API route, you can use `req.method` in your request handler, like so: +API 라우트에서 다양한 HTTP 메서드를 처리하려면 요청 핸들러에서 `req.method`를 사용할 수 있습니다. 예: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'POST') { - // Process a POST request + // POST 요청 처리 } else { - // Handle any other HTTP method + // 다른 HTTP 메서드 처리 } } ``` @@ -84,24 +82,24 @@ export default function handler(req: NextApiRequest, res: NextApiResponse) { ```js filename="pages/api/hello.js" switcher export default function handler(req, res) { if (req.method === 'POST') { - // Process a POST request + // POST 요청 처리 } else { - // Handle any other HTTP method + // 다른 HTTP 메서드 처리 } } ``` ## Request Helpers -API Routes provide built-in request helpers which parse the incoming request (`req`): +API Routes는 들어오는 요청(`req`)을 구문 분석하는 내장 요청 도우미를 제공합니다: -- `req.cookies` - An object containing the cookies sent by the request. Defaults to `{}` -- `req.query` - An object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}` -- `req.body` - An object containing the body parsed by `content-type`, or `null` if no body was sent +- `req.cookies` - 요청에 의해 전송된 쿠키를 포함하는 객체. 기본값은 `{}` +- `req.query` - [쿼리 문자열](https://en.wikipedia.org/wiki/Query_string) 을 포함하는 객체. 기본값은 `{}` +- `req.body` - `content-type`에 따라 구문 분석된 body를 포함하는 객체, body가 전송되지 않은 경우 `null` ### Custom config -Every API Route can export a `config` object to change the default configuration, which is the following: +모든 API 라우트는 기본 설정을 변경하기 위해 `config` 객체를 내보낼 수 있습니다. 기본 설정은 다음과 같습니다: ```js export const config = { @@ -110,14 +108,14 @@ export const config = { sizeLimit: '1mb', }, }, - // Specifies the maximum allowed duration for this function to execute (in seconds) + // 이 함수가 실행되는 최대 허용 시간을 지정함 (초 단위) maxDuration: 5, } ``` -`bodyParser` is automatically enabled. If you want to consume the body as a `Stream` or with [`raw-body`](https://www.npmjs.com/package/raw-body), you can set this to `false`. +`bodyParser`는 자동으로 활성화됩니다. body를 `Stream`으로 소비하거나 [raw-body](https://www.npmjs.com/package/raw-body) 로 소비하려면 이를 `false`로 설정할 수 있습니다. -One use case for disabling the automatic `bodyParsing` is to allow you to verify the raw body of a **webhook** request, for example [from GitHub](https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github). +자동 `bodyParsing`을 비활성화하는 한 가지 사용 사례는 예를 들어 [GitHub](https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github) **웹훅** 요청의 원본 body를 확인할 수 있도록 하는 것입니다. ```js export const config = { @@ -127,7 +125,7 @@ export const config = { } ``` -`bodyParser.sizeLimit` is the maximum size allowed for the parsed body, in any format supported by [bytes](https://github.com/visionmedia/bytes.js), like so: +`bodyParser.sizeLimit`은 [bytes](https://github.com/visionmedia/bytes.js) 가 지원하는 형식으로 구문 분석된 body의 최대 크기입니다. 예를 들어: ```js export const config = { @@ -139,7 +137,7 @@ export const config = { } ``` -`externalResolver` is an explicit flag that tells the server that this route is being handled by an external resolver like _express_ or _connect_. Enabling this option disables warnings for unresolved requests. +`externalResolver`는 이 라우트가 _express_ 또는 *connect*와 같은 외부 리졸버에 의해 처리되고 있음을 서버에 명시적으로 알리는 플래그입니다. 이 옵션을 활성화하면 해결되지 않은 요청에 대한 경고가 비활성화됩니다. ```js export const config = { @@ -149,9 +147,9 @@ export const config = { } ``` -`responseLimit` is automatically enabled, warning when an API Routes' response body is over 4MB. +`responseLimit`는 자동으로 활성화되며, API 라우트의 응답 body가 4MB를 초과할 경우 경고가 표시됩니다. -If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to `false`. +서버리스 환경에서 Next.js를 사용하지 않고, CDN이나 전용 미디어 호스트를 사용하지 않는 경우의 성능 영향을 이해하는 경우, 이 제한을 `false`로 설정할 수 있습니다. ```js export const config = { @@ -161,8 +159,8 @@ export const config = { } ``` -`responseLimit` can also take the number of bytes or any string format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. -This value will be the maximum response size before a warning is displayed. Default is 4MB. (see above) +`responseLimit`은 또한 `bytes`에서 지원하는 형식의 바이트 수 또는 문자열 형식을 취할 수 있습니다. 예를 들어 `1000`, `'500kb'` 또는 `'3mb'` 등이 있습니다. +이 값은 경고가 표시되기 전에 응답 크기의 최대값입니다. 기본값은 4MB입니다. (위 참조) ```js export const config = { @@ -174,21 +172,21 @@ export const config = { ## Response Helpers -The [Server Response object](https://nodejs.org/api/http.html#http_class_http_serverresponse), (often abbreviated as `res`) includes a set of Express.js-like helper methods to improve the developer experience and increase the speed of creating new API endpoints. +[서버 응답 객체](https://nodejs.org/api/http.html#http_class_http_serverresponse) (종종 `res`로 약칭됨)에는 개발자 경험을 개선하고 새로운 API 엔드포인트를 생성하는 속도를 높이기 위한 Express.js와 유사한 도우미 메서드 세트가 포함되어 있습니다. -The included helpers are: +포함된 도우미는 다음과 같습니다: -- `res.status(code)` - A function to set the status code. `code` must be a valid [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) -- `res.json(body)` - Sends a JSON response. `body` must be a [serializable object](https://developer.mozilla.org/docs/Glossary/Serialization) -- `res.send(body)` - Sends the HTTP response. `body` can be a `string`, an `object` or a `Buffer` -- `res.redirect([status,] path)` - Redirects to a specified path or URL. `status` must be a valid [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). If not specified, `status` defaults to "307" "Temporary redirect". -- `res.revalidate(urlPath)` - [Revalidate a page on demand](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation) using `getStaticProps`. `urlPath` must be a `string`. +- `res.status(code)` - 상태 코드를 설정하는 함수. `code`는 유효한 [HTTP 상태 코드](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) 여야 합니다 +- `res.json(body)` - JSON 응답을 보냅니다. `body`는 [직렬화 가능한 객체](https://developer.mozilla.org/docs/Glossary/Serialization) 여야 합니다 +- `res.send(body)` - HTTP 응답을 보냅니다. `body`는 `string`, `object` 또는 `Buffer`일 수 있음 +- `res.redirect([status,] path)` - 지정된 경로 또는 URL로 리디렉션합니다. `status`는 유효한 [HTTP 상태 코드](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) 여야 하며, 지정되지 않으면 기본값은 "307" "임시 리디렉션"입니다. +- `res.revalidate(urlPath)` - `getStaticProps`를 사용하여 [페이지를 필요에 따라 재검증](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation) 합니다. `urlPath`는 `string`이어야 합니다. ### Setting the status code of a response -When sending a response back to the client, you can set the status code of the response. +클라이언트에 응답을 보낼 때 응답의 상태 코드를 설정할 수 있습니다. -The following example sets the status code of the response to `200` (`OK`) and returns a `message` property with the value of `Hello from Next.js!` as a JSON response: +다음 예제는 응답의 상태 코드를 `200` (`OK`)으로 설정하고 `Hello from Next.js!` 값의 `message` 프로퍼티와 함께 JSON 응답을 반환합니다: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -213,10 +211,10 @@ export default function handler(req, res) { ### Sending a JSON response -When sending a response back to the client you can send a JSON response, this must be a [serializable object](https://developer.mozilla.org/docs/Glossary/Serialization). -In a real world application you might want to let the client know the status of the request depending on the result of the requested endpoint. +클라이언트에 응답을 보낼 때 JSON 응답을 보낼 수 있습니다. 이는 [직렬화 가능한 객체](https://developer.mozilla.org/docs/Glossary/Serialization) 여야 합니다. +실제 애플리케이션에서는 요청된 엔드포인트의 결과에 따라 요청의 상태를 클라이언트에 알리고자 할 수 있습니다. -The following example sends a JSON response with the status code `200` (`OK`) and the result of the async operation. It's contained in a try catch block to handle any errors that may occur, with the appropriate status code and error message caught and sent back to the client: +다음 예제는 상태 코드 `200` (`OK`)와 비동기 작업의 결과를 포함한 JSON 응답을 보냅니다. 오류가 발생할 수 있는 상황을 처리하기 위해 try catch 블록에 포함되어 있으며, 적절한 상태 코드와 함께 잡힌 오류 메시지를 클라이언트에 다시 보냅니다: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -229,7 +227,7 @@ export default async function handler( const result = await someAsyncOperation() res.status(200).json({ result }) } catch (err) { - res.status(500).json({ error: 'failed to load data' }) + res.status(500).json({ error: '데이터를 불러오는 데 실패했습니다.' }) } } ``` @@ -240,16 +238,16 @@ export default async function handler(req, res) { const result = await someAsyncOperation() res.status(200).json({ result }) } catch (err) { - res.status(500).json({ error: 'failed to load data' }) + res.status(500).json({ error: '데이터를 불러오는 데 실패했습니다.' }) } } ``` ### Sending a HTTP response -Sending an HTTP response works the same way as when sending a JSON response. The only difference is that the response body can be a `string`, an `object` or a `Buffer`. +HTTP 응답을 보내는 것은 JSON 응답을 보내는 것과 동일하게 작동합니다. 유일한 차이점은 응답 body가 `string`, `object` 또는 `Buffer`일 수 있다는 것입니다. -The following example sends a HTTP response with the status code `200` (`OK`) and the result of the async operation. +다음 예제는 상태 코드 `200` (`OK`)와 비동기 작업의 결과를 포함한 HTTP 응답을 보냅니다. ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -262,7 +260,7 @@ export default async function handler( const result = await someAsyncOperation() res.status(200).send({ result }) } catch (err) { - res.status(500).send({ error: 'failed to fetch data' }) + res.status(500).send({ error: '데이터를 가져오는 데 실패했습니다' }) } } ``` @@ -273,16 +271,16 @@ export default async function handler(req, res) { const result = await someAsyncOperation() res.status(200).send({ result }) } catch (err) { - res.status(500).send({ error: 'failed to fetch data' }) + res.status(500).send({ error: '데이터를 가져오는 데 실패했습니다' }) } } ``` ### Redirects to a specified path or URL -Taking a form as an example, you may want to redirect your client to a specified path or URL once they have submitted the form. +양식을 예로 들어, 양식을 제출한 후 클라이언트를 지정된 경로 또는 URL로 리디렉션하고자 할 수 있습니다. -The following example redirects the client to the `/` path if the form is successfully submitted: +다음 예제는 양식이 성공적으로 제출되면 클라이언트를 `/` 경로로 리디렉션합니다: ```ts filename="pages/api/hello.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -297,7 +295,7 @@ export default async function handler( await handleFormInputAsync({ name, message }) res.redirect(307, '/') } catch (err) { - res.status(500).send({ error: 'Failed to fetch data' }) + res.status(500).send({ error: '데이터를 가져오는 데 실패했습니다' }) } } ``` @@ -310,14 +308,14 @@ export default async function handler(req, res) { await handleFormInputAsync({ name, message }) res.redirect(307, '/') } catch (err) { - res.status(500).send({ error: 'failed to fetch data' }) + res.status(500).send({ error: '데이터를 가져오는 데 실패했습니다' }) } } ``` ### Adding TypeScript types -You can make your API Routes more type-safe by importing the `NextApiRequest` and `NextApiResponse` types from `next`, in addition to those, you can also type your response data: +`NextApiRequest` 및 `NextApiResponse` 타입을 `next`에서 가져와 API Routes를 더 타입 안정적으로 만들 수 있습니다. 추가로, 응답 데이터도 타입 지정할 수 있습니다: ```ts import type { NextApiRequest, NextApiResponse } from 'next' @@ -334,11 +332,11 @@ export default function handler( } ``` -> **Good to know**: The body of `NextApiRequest` is `any` because the client may include any payload. You should validate the type/shape of the body at runtime before using it. +> **Good to know** : `NextApiRequest`의 body는 `any`입니다. 이는 클라이언트가 임의의 페이로드를 포함할 수 있기 때문입니다. body를 사용하기 전에 런타임에서 body의 타입/형태를 검증해야 합니다. ## Dynamic API Routes -API Routes support [dynamic routes](/docs/pages/building-your-application/routing/dynamic-routes), and follow the same file naming rules used for `pages/`. +API Routes는 [dynamic routes](/docs/pages/building-your-application/routing/dynamic-routes) 를 지원하며, `pages/`에 사용된 파일 명명 규칙을 따릅니다. ```ts filename="pages/api/post/[pid].ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -356,29 +354,29 @@ export default function handler(req, res) { } ``` -Now, a request to `/api/post/abc` will respond with the text: `Post: abc`. +이제 `/api/post/abc`로의 요청은 `Post: abc`라는 텍스트로 응답합니다. ### Catch all API routes -API Routes can be extended to catch all paths by adding three dots (`...`) inside the brackets. For example: +API Routes는 괄호 안에 세 개의 점(`...`)을 추가하여 모든 경로를 포착하도록 확장할 수 있습니다. 예: -- `pages/api/post/[...slug].js` matches `/api/post/a`, but also `/api/post/a/b`, `/api/post/a/b/c` and so on. +- `pages/api/post/[...slug].js`는 `/api/post/a`와 일치하지만, `/api/post/a/b`, `/api/post/a/b/c` 등과도 일치합니다. -> **Good to know**: You can use names other than `slug`, such as: `[...param]` +> **Good to know** : `slug` 외에도 `[...param]`과 같은 이름을 사용할 수 있습니다. -Matched parameters will be sent as a query parameter (`slug` in the example) to the page, and it will always be an array, so, the path `/api/post/a` will have the following `query` object: +일치하는 매개변수는 페이지에 쿼리 매개변수로 전송되며(예제에서는 `slug`), 항상 배열 형태로 전송됩니다. 따라서 `/api/post/a` 경로는 다음과 같은 `query` 객체를 가집니다: ```json { "slug": ["a"] } ``` -And in the case of `/api/post/a/b`, and any other matching path, new parameters will be added to the array, like so: +그리고 `/api/post/a/b` 및 다른 일치하는 경로의 경우, 새로운 매개변수가 배열에 추가됩니다. 예: ```json { "slug": ["a", "b"] } ``` -For example: +예를 들어: ```ts filename="pages/api/post/[...slug].ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -396,33 +394,33 @@ export default function handler(req, res) { } ``` -Now, a request to `/api/post/a/b/c` will respond with the text: `Post: a, b, c`. +이제 `/api/post/a/b/c`로의 요청은 `Post: a, b, c`라는 텍스트로 응답합니다. ### Optional catch all API routes -Catch all routes can be made optional by including the parameter in double brackets (`[[...slug]]`). +모든 경로 포착 라우트를 선택적 포착 라우트로 만들려면 매개변수를 이중 괄호(`[[...slug]]`)에 포함합니다. -For example, `pages/api/post/[[...slug]].js` will match `/api/post`, `/api/post/a`, `/api/post/a/b`, and so on. +예를 들어, `pages/api/post/[[...slug]].js`는 `/api/post`, `/api/post/a`, `/api/post/a/b` 등과 일치합니다. -The main difference between catch all and optional catch all routes is that with optional, the route without the parameter is also matched (`/api/post` in the example above). +모든 경로 포착 라우트와 선택적 모든 경로 포착 라우트의 주요 차이점은 매개변수 없이도 경로가 일치한다는 점입니다(위 예제에서는 `/api/post`). -The `query` objects are as follows: +`query` 객체는 다음과 같습니다: ```json -{ } // GET `/api/post` (empty object) -{ "slug": ["a"] } // `GET /api/post/a` (single-element array) -{ "slug": ["a", "b"] } // `GET /api/post/a/b` (multi-element array) +{ } // `GET /api/post` (빈 객체) +{ "slug": ["a"] } // `GET /api/post/a` (단일 요소 배열) +{ "slug": ["a", "b"] } // `GET /api/post/a/b` (다중 요소 배열) ``` ### Caveats -- Predefined API routes take precedence over dynamic API routes, and dynamic API routes over catch all API routes. Take a look at the following examples: - - `pages/api/post/create.js` - Will match `/api/post/create` - - `pages/api/post/[pid].js` - Will match `/api/post/1`, `/api/post/abc`, etc. But not `/api/post/create` - - `pages/api/post/[...slug].js` - Will match `/api/post/1/2`, `/api/post/a/b/c`, etc. But not `/api/post/create`, `/api/post/abc` +- 미리 정의된 API 라우트는 동적 API 라우트보다 우선하며, 동적 API 라우트는 모든 경로 포착 API 라우트보다 우선합니다. 다음 예제를 참조하세요: +- `pages/api/post/create.js` - `/api/post/create`와 일치합니다. +- `pages/api/post/[pid].js` - `/api/post/1`, `/api/post/abc` 등과 일치하지만 `/api/post/create`와는 일치하지 않습니다. +- `pages/api/post/[...slug].js` - `/api/post/1/2`, `/api/post/a/b/c` 등과 일치하지만 `/api/post/create`, `/api/post/abc`와는 일치하지 않습니다. ## Edge API Routes -If you would like to use API Routes with the Edge Runtime, we recommend incrementally adopting the App Router and using [Route Handlers](/docs/app/building-your-application/routing/route-handlers) instead. +API Routes를 Edge Runtime과 함께 사용하고자 하는 경우, 점진적으로 App Router를 도입하고 [Route Handlers](/docs/app/building-your-application/routing/route-handlers) 를 사용하는 것을 권장합니다. -The Route Handlers function signature is isomorphic, meaning you can use the same function for both Edge and Node.js runtimes. +Route Handlers 함수 시그니처는 isomorphic으로, Edge와 Node.js 런타임 모두에 동일한 함수를 사용할 수 있습니다. diff --git a/pages/docs/pages/building-your-application/routing/internationalization.mdx b/pages/docs/pages/building-your-application/routing/internationalization.mdx index b083f00..c972829 100644 --- a/pages/docs/pages/building-your-application/routing/internationalization.mdx +++ b/pages/docs/pages/building-your-application/routing/internationalization.mdx @@ -4,8 +4,6 @@ nav_title: Internationalization description: Next.js has built-in support for internationalized routing and language detection. Learn more here. --- -{/* TODO: 번역이 필요합니다. */} - # Internationalization (i18n) Routing
    @@ -15,37 +13,35 @@ description: Next.js has built-in support for internationalized routing and lang
    -Next.js has built-in support for internationalized ([i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization#Naming)) routing since `v10.0.0`. You can provide a list of locales, the default locale, and domain-specific locales and Next.js will automatically handle the routing. +Next.js는 `v10.0.0`부터 기본적으로 국제화([i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization#Naming)) 라우팅을 지원합니다. 로케일 목록, 기본 로케일 및 도메인별 로케일을 제공하면 Next.js가 자동으로 라우팅을 처리합니다. -The i18n routing support is currently meant to complement existing i18n library solutions like [`react-intl`](https://formatjs.io/docs/getting-started/installation), [`react-i18next`](https://react.i18next.com/), [`lingui`](https://lingui.dev/), [`rosetta`](https://github.com/lukeed/rosetta), [`next-intl`](https://github.com/amannn/next-intl), [`next-translate`](https://github.com/aralroca/next-translate), [`next-multilingual`](https://github.com/Avansai/next-multilingual), [`tolgee`](https://tolgee.io/integrations/next), [`paraglide-next`](https://inlang.com/m/osslbuzt/paraglide-next-i18n) and others by streamlining the routes and locale parsing. +현재 i18n 라우팅 지원은 라우트 및 로케일 구문 분석을 간소화하여 [`react-intl`](https://formatjs.io/docs/getting-started/installation), [`react-i18next`](https://react.i18next.com/), [`lingui`](https://lingui.dev/), [`rosetta`](https://github.com/lukeed/rosetta), [`next-intl`](https://github.com/amannn/next-intl), [`next-translate`](https://github.com/aralroca/next-translate), [`next-multilingual`](https://github.com/Avansai/next-multilingual), [`tolgee`](https://tolgee.io/integrations/next), [`paraglide-next`](https://inlang.com/m/osslbuzt/paraglide-next-i18n) 등과 같은 기존 i18n 라이브러리 솔루션을 보완하기 위한 것입니다. ## Getting started -To get started, add the `i18n` config to your `next.config.js` file. +시작하기 위해 `next.config.js` 파일에 `i18n` 설정을 추가합니다. -Locales are [UTS Locale Identifiers](https://www.unicode.org/reports/tr35/tr35-59/tr35.html#Identifiers), a standardized format for defining locales. +로케일은 [UTS 로케일 식별자](https://www.unicode.org/reports/tr35/tr35-59/tr35.html#Identifiers)로, 로케일을 정의하기 위한 표준화된 형식입니다. -Generally a Locale Identifier is made up of a language, region, and script separated by a dash: `language-region-script`. The region and script are optional. An example: +일반적으로 로케일 식별자는 언어, 지역 및 스크립트로 구성되며, 이들은 대시로 구분됩니다: `language-region-script`. 지역과 스크립트는 선택 사항입니다. 예시: -- `en-US` - English as spoken in the United States -- `nl-NL` - Dutch as spoken in the Netherlands -- `nl` - Dutch, no specific region +- `en-US` - 미국에서 사용되는 영어 +- `nl-NL` - 네덜란드에서 사용되는 네덜란드어 +- `nl` - 특정 지역이 없는 네덜란드어 -If user locale is `nl-BE` and it is not listed in your configuration, they will be redirected to `nl` if available, or to the default locale otherwise. -If you don't plan to support all regions of a country, it is therefore a good practice to include country locales that will act as fallbacks. +사용자의 로케일이 `nl-BE`이고, 해당 로케일이 설정에 포함되지 않은 경우, 사용자는 `nl`이 사용 가능하다면 `nl`로 리디렉션되거나 그렇지 않으면 기본 로케일로 리디렉션됩니다. +특정 국가의 모든 지역을 지원할 계획이 아니라면, fallback 역할을 할 국가 로케일을 포함하는 것이 좋습니다. ```js filename="next.config.js" module.exports = { i18n: { - // These are all the locales you want to support in - // your application + // 애플리케이션에서 지원하려는 모든 로케일이 포함됩니다. locales: ['en-US', 'fr', 'nl-NL'], - // This is the default locale you want to be used when visiting - // a non-locale prefixed path e.g. `/hello` + // 로케일 접두사가 없는 경로를 방문할 때 사용할 기본 로케일입니다. + // 예: `/hello` defaultLocale: 'en-US', - // This is a list of locale domains and the default locale they - // should handle (these are only required when setting up domain routing) - // Note: subdomains must be included in the domain value to be matched e.g. "fr.example.com". + // 로케일 도메인 목록과 각 도메인이 처리해야 할 기본 로케일입니다. (이는 도메인 라우팅을 설정할 때만 필요합니다.) + // 주의: 하위 도메인 또한 도메인 값에 포함되어야 합니다. 예: "fr.example.com" domains: [ { domain: 'example.com', @@ -58,8 +54,7 @@ module.exports = { { domain: 'example.fr', defaultLocale: 'fr', - // an optional http field can also be used to test - // locale domains locally with http instead of https + // 선택적으로 http 필드를 사용하여 로컬에서 https 대신 http로 로케일 도메인을 테스트할 수 있습니다. http: true, }, ], @@ -69,11 +64,11 @@ module.exports = { ## Locale Strategies -There are two locale handling strategies: Sub-path Routing and Domain Routing. +로케일 처리 전략에는 두 가지가 있습니다: 하위 경로 라우팅과 도메인 라우팅입니다. ### Sub-path Routing -Sub-path Routing puts the locale in the url path. +하위 경로 라우팅은 URL 경로에 로케일을 포함시킵니다. ```js filename="next.config.js" module.exports = { @@ -84,17 +79,17 @@ module.exports = { } ``` -With the above configuration `en-US`, `fr`, and `nl-NL` will be available to be routed to, and `en-US` is the default locale. If you have a `pages/blog.js` the following urls would be available: +위 설정에서는 `en-US`, `fr`, `nl-NL`로 라우팅이 가능하며, `en-US`가 기본 로케일입니다. `pages/blog.js`가 있는 경우, 다음과 같은 URL을 사용할 수 있습니다: - `/blog` - `/fr/blog` - `/nl-nl/blog` -The default locale does not have a prefix. +기본 로케일에는 접두사가 없습니다. ### Domain Routing -By using domain routing you can configure locales to be served from different domains: +도메인 라우팅을 사용하면 서로 다른 도메인에서 로케일을 제공하도록 설정할 수 있습니다: ```js filename="next.config.js" module.exports = { @@ -104,8 +99,8 @@ module.exports = { domains: [ { - // Note: subdomains must be included in the domain value to be matched - // e.g. www.example.com should be used if that is the expected hostname + // 주의: 하위 도메인 또한 도메인 값에 포함되어야 합니다. + // 예: 예상되는 호스트명이 www.example.com인 경우 해당 도메인을 사용해야 합니다. domain: 'example.com', defaultLocale: 'en-US', }, @@ -116,8 +111,7 @@ module.exports = { { domain: 'example.nl', defaultLocale: 'nl-NL', - // specify other locales that should be redirected - // to this domain + // 이 도메인으로 리디렉션되어야 하는 로케일을 지정합니다. locales: ['nl-BE'], }, ], @@ -125,7 +119,7 @@ module.exports = { } ``` -For example if you have `pages/blog.js` the following urls will be available: +예를 들어 `pages/blog.js`가 있는 경우, 다음과 같은 URL을 사용할 수 있습니다: - `example.com/blog` - `www.example.com/blog` @@ -135,22 +129,22 @@ For example if you have `pages/blog.js` the following urls will be available: ## Automatic Locale Detection -When a user visits the application root (generally `/`), Next.js will try to automatically detect which locale the user prefers based on the [`Accept-Language`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Accept-Language) header and the current domain. +사용자가 애플리케이션의 루트(일반적으로 `/`)를 방문하면, Next.js는 [`Accept-Language`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Accept-Language) 헤더와 현재 도메인을 기반으로 사용자가 선호하는 로케일을 자동으로 감지합니다. -If a locale other than the default locale is detected, the user will be redirected to either: +기본 로케일이 아닌 다른 로케일이 감지되면, 사용자는 다음 중 하나로 리디렉션됩니다: -- **When using Sub-path Routing:** The locale prefixed path -- **When using Domain Routing:** The domain with that locale specified as the default +- **하위 경로 라우팅을 사용하는 경우:** 로케일 접두사가 있는 경로 +- **도메인 라우팅을 사용하는 경우:** 해당 로케일이 기본값으로 지정된 도메인 -When using Domain Routing, if a user with the `Accept-Language` header `fr;q=0.9` visits `example.com`, they will be redirected to `example.fr` since that domain handles the `fr` locale by default. +도메인 라우팅을 사용하는 경우, `Accept-Language` 헤더가 `fr;q=0.9`인 사용자가 `example.com`을 방문하면, 해당 도메인이 기본적으로 `fr` 로케일을 처리하기 때문에 `example.fr`로 리디렉션됩니다. -When using Sub-path Routing, the user would be redirected to `/fr`. +하위 경로 라우팅을 사용하는 경우, 사용자는 `/fr`로 리디렉션됩니다. ### Prefixing the Default Locale -With Next.js 12 and [Middleware](/docs/pages/building-your-application/routing/middleware), we can add a prefix to the default locale with a [workaround](https://github.com/vercel/next.js/discussions/18419). +Next.js 12와 [미들웨어](/docs/pages/building-your-application/routing/middleware)를 사용하면 [우회 방법](https://github.com/vercel/next.js/discussions/18419)을 통해 기본 로케일에 접두사를 추가할 수 있습니다. -For example, here's a `next.config.js` file with support for a few languages. Note the `"default"` locale has been added intentionally. +예를 들어, 다음은 몇 가지 언어를 지원하는 `next.config.js` 파일입니다. 여기서 `"default"` 로케일은 의도적으로 추가되었습니다. ```js filename="next.config.js" module.exports = { @@ -163,7 +157,7 @@ module.exports = { } ``` -Next, we can use [Middleware](/docs/pages/building-your-application/routing/middleware) to add custom routing rules: +다음으로, [미들웨어](/docs/pages/building-your-application/routing/middleware)를 사용하여 사용자 정의 라우팅 규칙을 추가할 수 있습니다: ```ts filename="middleware.ts" import { NextRequest, NextResponse } from 'next/server' @@ -192,11 +186,11 @@ export async function middleware(req: NextRequest) { } ``` -This [Middleware](/docs/pages/building-your-application/routing/middleware) skips adding the default prefix to [API Routes](/docs/pages/building-your-application/routing/api-routes) and [public](/docs/pages/building-your-application/optimizing/static-assets) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`. +이 [미들웨어](/docs/pages/building-your-application/routing/middleware)는 [API 라우트](/docs/pages/building-your-application/routing/api-routes) 및 폰트나 이미지 같은 [public](/docs/pages/building-your-application/optimizing/static-assets) 파일에 기본 접두사를 추가하지 않습니다. 기본 로케일로 요청이 들어오면, 접두사 `/en`으로 리디렉션합니다. ### Disabling Automatic Locale Detection -The automatic locale detection can be disabled with: +자동 로케일 감지는 다음과 같이 비활성화할 수 있습니다: ```js filename="next.config.js" module.exports = { @@ -206,25 +200,25 @@ module.exports = { } ``` -When `localeDetection` is set to `false` Next.js will no longer automatically redirect based on the user's preferred locale and will only provide locale information detected from either the locale based domain or locale path as described above. +`localeDetection`이 `false`로 설정되면, Next.js는 사용자가 선호하는 로케일에 따라 자동으로 리디렉션하지 않습니다. 대신, 로케일 기반 도메인이나 로케일 경로에서 감지된 로케일 정보만을 사용하여 작동합니다. ## Accessing the locale information -You can access the locale information via the Next.js router. For example, using the [`useRouter()`](/docs/pages/api-reference/functions/use-router) hook the following properties are available: +Next.js 라우터를 통해 로케일 정보를 접근할 수 있습니다. 예를 들어, [`useRouter()`](/docs/pages/api-reference/functions/use-router) 훅을 사용하면 다음 속성에 접근할 수 있습니다: -- `locale` contains the currently active locale. -- `locales` contains all configured locales. -- `defaultLocale` contains the configured default locale. +- `locale`은 현재 활성화된 로케일을 포함합니다. +- `locales`는 설정된 모든 로케일을 포함합니다. +- `defaultLocale`은 설정된 기본 로케일을 포함합니다. -When [pre-rendering](/docs/pages/building-your-application/rendering/static-site-generation) pages with `getStaticProps` or `getServerSideProps`, the locale information is provided in [the context](/docs/pages/building-your-application/data-fetching/get-static-props) provided to the function. +`getStaticProps`나 `getServerSideProps`를 사용하여 페이지를 [사전 렌더링](/docs/pages/building-your-application/rendering/static-site-generation) 할 때, 로케일 정보는 함수에 제공된 [컨텍스트](/docs/pages/building-your-application/data-fetching/get-static-props)에서 확인할 수 있습니다. -When leveraging `getStaticPaths`, the configured locales are provided in the context parameter of the function under `locales` and the configured defaultLocale under `defaultLocale`. +`getStaticPaths`를 활용하는 경우, 설정된 로케일은 함수의 컨텍스트 파라미터의 `locales`에서 제공되며, 기본 로케일은 `defaultLocale`에서 제공됩니다. ## Transition between locales -You can use `next/link` or `next/router` to transition between locales. +`next/link` 또는 `next/router`를 사용하여 로케일 간에 전환이 가능합니다. -For `next/link`, a `locale` prop can be provided to transition to a different locale from the currently active one. If no `locale` prop is provided, the currently active `locale` is used during client-transitions. For example: +`next/link`의 경우, `locale` 속성을 제공하여 현재 활성화된 로케일에서 다른 로케일로 전환할 수 있습니다. `locale` 속성이 제공되지 않으면, 클라이언트 전환 중에 현재 활성화된 로케일이 사용됩니다. 예를 들어: ```jsx import Link from 'next/link' @@ -238,7 +232,7 @@ export default function IndexPage(props) { } ``` -When using the `next/router` methods directly, you can specify the `locale` that should be used via the transition options. For example: +`next/router` 메서드를 직접 사용하는 경우, 전환 옵션을 통해 사용할 `locale`을 지정할 수 있습니다. 예를 들어: ```jsx import { useRouter } from 'next/router' @@ -258,19 +252,19 @@ export default function IndexPage(props) { } ``` -Note that to handle switching only the `locale` while preserving all routing information such as [dynamic route](/docs/pages/building-your-application/routing/dynamic-routes) query values or hidden href query values, you can provide the `href` parameter as an object: +`locale`만 전환하면서 [동적 라우트](/docs/pages/building-your-application/routing/dynamic-routes) 쿼리 값이나 숨겨진 href 쿼리 값과 같은 모든 라우팅 정보를 유지하려면 `href` 파라미터를 객체로 제공할 수 있습니다. ```jsx import { useRouter } from 'next/router' const router = useRouter() const { pathname, asPath, query } = router -// change just the locale and maintain all other route information including href's query +// 로케일만 변경하고 href의 쿼리를 포함한 모든 라우트 정보를 유지합니다. router.push({ pathname, query }, asPath, { locale: nextLocale }) ``` -See [here](/docs/pages/api-reference/functions/use-router#with-url-object) for more information on the object structure for `router.push`. +`router.push`의 객체 구조에 대한 자세한 내용은 [여기](/docs/pages/api-reference/functions/use-router#with-url-object)에서 확인할 수 있습니다. -If you have a `href` that already includes the locale you can opt-out of automatically handling the locale prefixing: +이미 로케일이 포함된 `href`를 가지고 있다면, 로케일 접두사를 자동으로 처리하지 않도록 선택할 수 있습니다: ```jsx import Link from 'next/link' @@ -286,29 +280,29 @@ export default function IndexPage(props) { ## Leveraging the `NEXT_LOCALE` cookie -Next.js allows setting a `NEXT_LOCALE=the-locale` cookie, which takes priority over the accept-language header. This cookie can be set using a language switcher and then when a user comes back to the site it will leverage the locale specified in the cookie when redirecting from `/` to the correct locale location. +Next.js에서는 `NEXT_LOCALE=the-locale` 쿠키를 설정할 수 있으며, 이 쿠키는 `accept-language` 헤더보다 우선적으로 적용됩니다. 이 쿠키는 언어 전환 기능을 통해 설정할 수 있으며, 사용자가 사이트를 다시 방문할 때 `/`에서 해당 쿠키에 지정된 로케일로 리디렉션됩니다. -For example, if a user prefers the locale `fr` in their accept-language header but a `NEXT_LOCALE=en` cookie is set the `en` locale when visiting `/` the user will be redirected to the `en` locale location until the cookie is removed or expired. +예를 들어, 사용자의 `accept-language` 헤더에서 `fr` 로케일이 선호된다고 하더라도 `NEXT_LOCALE=en` 쿠키가 설정되어 있으면 사용자는 `/`를 방문할 때 `en` 로케일로 리디렉션됩니다. 이 쿠키가 제거되거나 만료될 때까지 사용자는 `en` 로케일로 리디렉션됩니다. ## Search Engine Optimization -Since Next.js knows what language the user is visiting it will automatically add the `lang` attribute to the `` tag. +Next.js는 사용자가 사용하는 언어를 인식하기 때문에 `` 태그에 자동으로 `lang` 속성을 추가합니다. -Next.js doesn't know about variants of a page so it's up to you to add the `hreflang` meta tags using [`next/head`](/docs/pages/api-reference/components/head). You can learn more about `hreflang` in the [Google Webmasters documentation](https://support.google.com/webmasters/answer/189077). +Next.js는 페이지의 여러 형태를 자동으로 인식하지 않으므로, [`next/head`](/docs/pages/api-reference/components/head)를 사용하여 `hreflang` 메타 태그를 추가해야 합니다. `hreflang`에 대한 자세한 내용은 [Google 웹마스터 문서](https://support.google.com/webmasters/answer/189077)를 참조하세요. ## How does this work with Static Generation? -> Note that Internationalized Routing does not integrate with [`output: 'export'`](/docs/pages/building-your-application/deploying/static-exports) as it does not leverage the Next.js routing layer. Hybrid Next.js applications that do not use `output: 'export'` are fully supported. +> 국제화된 라우팅은 Next.js 라우팅 레이어를 사용하지 않기 때문에 `output: 'export'`와 호환되지 않습니다. `output: 'export'`를 사용하지 않는 하이브리드 Next.js 애플리케이션은 완전히 지원됩니다. ### Dynamic Routes and `getStaticProps` Pages -For pages using `getStaticProps` with [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/pages/building-your-application/data-fetching/get-static-paths). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example: +`getStaticProps`와 [동적 라우트](/docs/pages/building-your-application/routing/dynamic-routes)를 사용하는 페이지의 경우, 사전 렌더링 하려는 페이지의 모든 로케일 정보를 [`getStaticPaths`](/docs/pages/building-your-application/data-fetching/get-static-paths)에서 반환해야 합니다. `paths`를 지정하는 `params` 객체와 함께, 렌더링 할 로케일을 나타내는 `locale` 필드를 반환할 수 있습니다. 예를 들어: ```jsx filename="pages/blog/[slug].js" export const getStaticPaths = ({ locales }) => { return { paths: [ - // if no `locale` is provided only the defaultLocale will be generated + // `locale`이 제공되지 않으면 기본 로케일만 생성됩니다. { params: { slug: 'post-1' }, locale: 'en-US' }, { params: { slug: 'post-1' }, locale: 'fr' }, ], @@ -317,24 +311,24 @@ export const getStaticPaths = ({ locales }) => { } ``` -For [Automatically Statically Optimized](/docs/pages/building-your-application/rendering/automatic-static-optimization) and non-dynamic `getStaticProps` pages, **a version of the page will be generated for each locale**. This is important to consider because it can increase build times depending on how many locales are configured inside `getStaticProps`. +[자동 정적 최적화](/docs/pages/building-your-application/rendering/automatic-static-optimization)가 되면서 `getStaticProps`를 사용하는 페이지의 경우, **각 로케일에 대한 페이지 버전이 생성됩니다.** 이는 `getStaticProps`에 설정된 로케일 수에 따라 빌드 시간이 증가할 수 있기 때문에 중요한 사항입니다. -For example, if you have 50 locales configured with 10 non-dynamic pages using `getStaticProps`, this means `getStaticProps` will be called 500 times. 50 versions of the 10 pages will be generated during each build. +예를 들어, 50개의 로케일이 설정된 상태에서 10개의 비동적 페이지가 `getStaticProps`를 사용하는 경우, 빌드 시 10개의 페이지에 각각 50가지 버전이 생성되므로 `getStaticProps`가 500번 호출됩니다. -To decrease the build time of dynamic pages with `getStaticProps`, use a [`fallback` mode](/docs/pages/api-reference/functions/get-static-paths#fallback-true). This allows you to return only the most popular paths and locales from `getStaticPaths` for prerendering during the build. Then, Next.js will build the remaining pages at runtime as they are requested. +동적 페이지의 빌드 시간을 줄이려면 `getStaticProps`와 함께 [`fallback` 모드](/docs/pages/api-reference/functions/get-static-paths#fallback-true)를 사용하는 것이 좋습니다. 이렇게 하면 `getStaticPaths`에서 가장 많이 사용되는 경로와 로케일을 반환할 수 있으며, Next.js는 나머지 페이지를 요청 시 런타임에 생성합니다. ### Automatically Statically Optimized Pages -For pages that are [automatically statically optimized](/docs/pages/building-your-application/rendering/automatic-static-optimization), a version of the page will be generated for each locale. +[자동 정적 최적화](/docs/pages/building-your-application/rendering/automatic-static-optimization)된 페이지의 경우, 각 로케일에 대한 페이지 버전이 생성됩니다. ### Non-dynamic getStaticProps Pages -For non-dynamic `getStaticProps` pages, a version is generated for each locale like above. `getStaticProps` is called with each `locale` that is being rendered. If you would like to opt-out of a certain locale from being pre-rendered, you can return `notFound: true` from `getStaticProps` and this variant of the page will not be generated. +비동적 `getStaticProps` 페이지의 경우, 위에서 설명한 대로 각 로케일에 대한 버전이 생성됩니다. `getStaticProps`는 렌더링 할 각 로케일에 대해 호출됩니다. 특정 로케일에 대한 사전 렌더링을 제외하고 싶다면, `getStaticProps`에서 `notFound: true`를 반환하면 해당 로케일의 페이지는 생성되지 않습니다. ```js export async function getStaticProps({ locale }) { - // Call an external API endpoint to get posts. - // You can use any data fetching library + // 외부 API 엔드 포인트를 호출하여 게시물을 가져옵니다. + // 원하는 데이터 fetching 라이브러리를 사용할 수 있습니다. const res = await fetch(`https://.../posts?locale=${locale}`) const posts = await res.json() @@ -344,8 +338,8 @@ export async function getStaticProps({ locale }) { } } - // By returning { props: posts }, the Blog component - // will receive `posts` as a prop at build time + // { props: posts }를 반환하면, Blog 컴포넌트는 + // 빌드 시 `posts`를 prop으로 받게 됩니다. return { props: { posts, @@ -356,7 +350,7 @@ export async function getStaticProps({ locale }) { ## Limits for the i18n config -- `locales`: 100 total locales -- `domains`: 100 total locale domain items +- `locales`: 총 100개의 로케일 +- `domains`: 총 100개의 로케일 도메인 항목 -> **Good to know**: These limits have been added initially to prevent potential [performance issues at build time](#dynamic-routes-and-getstaticprops-pages). You can workaround these limits with custom routing using [Middleware](/docs/pages/building-your-application/routing/middleware) in Next.js 12. +> **알아두면 좋은 정보**: 이 제한은 초기에 [빌드 시 발생할 수 있는 성능 문제](#dynamic-routes-and-getstaticprops-pages)를 방지하기 위해 추가되었습니다. Next.js 12의 [미들웨어](/docs/pages/building-your-application/routing/middleware)를 사용하여 이 제한을 우회할 수 있습니다. diff --git a/pages/docs/pages/building-your-application/routing/pages-and-layouts.mdx b/pages/docs/pages/building-your-application/routing/pages-and-layouts.mdx index 587fbb4..638bcb2 100644 --- a/pages/docs/pages/building-your-application/routing/pages-and-layouts.mdx +++ b/pages/docs/pages/building-your-application/routing/pages-and-layouts.mdx @@ -3,17 +3,15 @@ title: Pages and Layouts description: Create your first page and shared layout with the Pages Router. --- -{/* TODO: 번역이 필요합니다. */} - # Pages and Layouts -The Pages Router has a file-system based router built on the concept of pages. +페이지 라우터는 페이지 개념에 기반한 파일 시스템 기반 라우터를 가지고 있습니다. -When a file is added to the `pages` directory, it's automatically available as a route. +`pages` 디렉토리에 파일을 추가하면 자동으로 라우트로 사용 가능해집니다. -In Next.js, a **page** is a [React Component](https://react.dev/learn/your-first-component) exported from a `.js`, `.jsx`, `.ts`, or `.tsx` file in the `pages` directory. Each page is associated with a route based on its file name. +Next.js에서 **페이지**는 `pages` 디렉토리의 `.js`, `.jsx`, `.ts`, 또는 `.tsx` 파일에서 내보내진 [React 컴포넌트](https://react.dev/learn/your-first-component)입니다. 각 페이지는 파일 이름을 기반으로 한 라우트와 연결됩니다. -**Example**: If you create `pages/about.js` that exports a React component like below, it will be accessible at `/about`. +**예시**: 아래와 같이 React 컴포넌트를 내보내는 `pages/about.js`를 생성하면, `/about`에서 접근할 수 있습니다. ```jsx export default function About() { @@ -23,27 +21,27 @@ export default function About() { ## Index routes -The router will automatically route files named `index` to the root of the directory. +라우터는 `index`라는 이름의 파일을 디렉토리의 루트로 자동 라우팅합니다. - `pages/index.js` → `/` - `pages/blog/index.js` → `/blog` ## Nested routes -The router supports nested files. If you create a nested folder structure, files will automatically be routed in the same way still. +라우터는 중첩 파일을 지원합니다. 중첩 폴더 구조를 생성하면 파일들이 여전히 같은 방식으로 자동 라우팅됩니다. - `pages/blog/first-post.js` → `/blog/first-post` - `pages/dashboard/settings/username.js` → `/dashboard/settings/username` ## Pages with Dynamic Routes -Next.js supports pages with dynamic routes. For example, if you create a file called `pages/posts/[id].js`, then it will be accessible at `posts/1`, `posts/2`, etc. +Next.js는 동적 라우트를 가진 페이지를 지원합니다. 예를 들어, `pages/posts/[id].js`라는 파일을 생성하면, `posts/1`, `posts/2` 등에서 접근할 수 있습니다. -> To learn more about dynamic routing, check the [Dynamic Routing documentation](/docs/pages/building-your-application/routing/dynamic-routes). +> 동적 라우팅에 대해 더 알아보려면 [동적 라우팅 문서](/docs/pages/building-your-application/routing/dynamic-routes)를 확인하세요. ## Layout Pattern -The React model allows us to deconstruct a [page](/docs/pages/building-your-application/routing/pages-and-layouts) into a series of components. Many of these components are often reused between pages. For example, you might have the same navigation bar and footer on every page. +React 모델을 사용하면 [페이지](/docs/pages/building-your-application/routing/pages-and-layouts)를 여러 컴포넌트로 분해할 수 있습니다. 이 컴포넌트들은 종종 페이지 간에 재사용됩니다. 예를 들어, 모든 페이지에 같은 네비게이션 바와 푸터를 가질 수 있습니다. ```jsx filename="components/layout.js" import Navbar from './navbar' @@ -64,7 +62,7 @@ export default function Layout({ children }) { ### Single Shared Layout with Custom App -If you only have one layout for your entire application, you can create a [Custom App](/docs/pages/building-your-application/routing/custom-app) and wrap your application with the layout. Since the `` component is re-used when changing pages, its component state will be preserved (e.g. input values). +전체 애플리케이션에 하나의 레이아웃만 있는 경우, [커스텀 앱](/docs/pages/building-your-application/routing/custom-app)을 생성하고 애플리케이션을 레이아웃으로 감쌀 수 있습니다. 페이지 변경 시 `` 컴포넌트가 재사용되므로 컴포넌트 상태가 유지됩니다(예: input values). ```jsx filename="pages/_app.js" import Layout from '../components/layout' @@ -80,7 +78,7 @@ export default function MyApp({ Component, pageProps }) { ### Per-Page Layouts -If you need multiple layouts, you can add a property `getLayout` to your page, allowing you to return a React component for the layout. This allows you to define the layout on a _per-page basis_. Since we're returning a function, we can have complex nested layouts if desired. +여러 레이아웃이 필요한 경우, 페이지에 `getLayout` 속성을 추가하여 레이아웃을 반환할 수 있는 React 컴포넌트를 지정할 수 있습니다. 이를 통해 페이지별로 레이아웃을 정의할 수 있습니다. 함수를 반환하므로 원하는 경우 복잡한 중첩 레이아웃을 가질 수 있습니다. ```jsx filename="pages/index.js" @@ -89,7 +87,7 @@ import NestedLayout from '../components/nested-layout' export default function Page() { return ( - /** Your content */ + /** 여기에 내용을 넣으세요 */ ) } @@ -104,22 +102,22 @@ Page.getLayout = function getLayout(page) { ```jsx filename="pages/_app.js" export default function MyApp({ Component, pageProps }) { - // Use the layout defined at the page level, if available + // 가능하다면, 페이지 수준에서 정의된 레이아웃을 사용하세요 const getLayout = Component.getLayout ?? ((page) => page) return getLayout() } ``` -When navigating between pages, we want to _persist_ page state (input values, scroll position, etc.) for a Single-Page Application (SPA) experience. +페이지 간에 이동할 때, 단일 페이지 애플리케이션(SPA) 경험을 위해 페이지 상태(입력 값, 스크롤 위치 등)를 유지 하고자 합니다. -This layout pattern enables state persistence because the React component tree is maintained between page transitions. With the component tree, React can understand which elements have changed to preserve state. +이 레이아웃 패턴은 페이지 전환 사이에 React 컴포넌트 트리가 유지되므로 상태 유지를 가능하게 합니다. 컴포넌트 트리를 통해 React는 어떤 요소가 변경되었는지 파악하여 상태를 보존할 수 있습니다. -> **Good to know**: This process is called [reconciliation](https://react.dev/learn/preserving-and-resetting-state), which is how React understands which elements have changed. +> **알아두면 좋습니다**: 이 과정을 [재조정](https://react.dev/learn/preserving-and-resetting-state)이라고 하며, React가 어떤 요소가 변경되었는지 이해하는 방법입니다. ### With TypeScript -When using TypeScript, you must first create a new type for your pages which includes a `getLayout` function. Then, you must create a new type for your `AppProps` which overrides the `Component` property to use the previously created type. +타입스크립트를 사용할 때는 먼저 `getLayout` 함수를 포함하는 페이지의 새 타입을 생성해야 합니다. 그런 다음, 이전에 생성된 타입을 사용하도록 `Component` 속성을 오버라이드하는 `AppProps`의 새 타입을 생성해야 합니다. ```tsx filename="pages/index.tsx" switcher import type { ReactElement } from 'react' @@ -175,7 +173,7 @@ type AppPropsWithLayout = AppProps & { } export default function MyApp({ Component, pageProps }: AppPropsWithLayout) { - // Use the layout defined at the page level, if available + // 가능하다면, 페이지 수준에서 정의된 레이아웃을 사용하세요 const getLayout = Component.getLayout ?? ((page) => page) return getLayout() @@ -184,7 +182,7 @@ export default function MyApp({ Component, pageProps }: AppPropsWithLayout) { ```jsx filename="pages/_app.js" switcher export default function MyApp({ Component, pageProps }) { - // Use the layout defined at the page level, if available + // 가능하다면, 페이지 수준에서 정의된 레이아웃을 사용하세요 const getLayout = Component.getLayout ?? ((page) => page) return getLayout() @@ -193,7 +191,7 @@ export default function MyApp({ Component, pageProps }) { ### Data Fetching -Inside your layout, you can fetch data on the client-side using `useEffect` or a library like [SWR](https://swr.vercel.app/). Because this file is not a [Page](/docs/pages/building-your-application/routing/pages-and-layouts), you cannot use `getStaticProps` or `getServerSideProps` currently. +레이아웃 내에서 `useEffect` 또는 [SWR](https://swr.vercel.app/) 같은 라이브러리를 사용하여 클라이언트 측에서 데이터를 가져올 수 있습니다. 이 파일이 [페이지](/docs/pages/building-your-application/routing/pages-and-layouts)가 아니기 때문에 현재 `getStaticProps`나 `getServerSideProps`는 사용할 수 없습니다. ```jsx filename="components/layout.js" import useSWR from 'swr' diff --git a/pages/docs/pages/building-your-application/upgrading/version-9.mdx b/pages/docs/pages/building-your-application/upgrading/version-9.mdx index 1c6c4fe..e037a1d 100644 --- a/pages/docs/pages/building-your-application/upgrading/version-9.mdx +++ b/pages/docs/pages/building-your-application/upgrading/version-9.mdx @@ -4,11 +4,9 @@ nav_title: Version 9 description: Upgrade your Next.js Application from Version 8 to Version 9. --- -{/* TODO: 번역이 필요합니다. */} - # Upgrading to Version 9 -To upgrade to version 9, run the following command: +버전 9로 업그레이드하려면 아래의 명령어를 실행하세요: ```bash filename="Terminal" npm i next@9 @@ -26,27 +24,27 @@ pnpm up next@9 bun add next@9 ``` -> **Good to know:** If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their corresponding versions. +> **알아두면 좋은 사항:** TypeScript를 사용하는 경우, `@types/react` 및 `@types/react-dom`도 해당 버전으로 업그레이드해야 합니다. ## Production Deployment on Vercel -If you previously configured `routes` in your `vercel.json` file for dynamic routes, these rules can be removed when leveraging Next.js 9's new [Dynamic Routing feature](/docs/pages/building-your-application/routing/dynamic-routes). +과거에 `vercel.json` 파일에서 동적 경로를 위해 `routes`를 구성했다면, Next.js 9의 새로운 기능인 [Dynamic Routing feature](/docs/pages/building-your-application/routing/dynamic-routes)을 활용해 이러한 규칙을 제거할 수 있습니다. -Next.js 9's dynamic routes are **automatically configured on [Vercel](https://vercel.com/)** and do not require any `vercel.json` customization. +Next.js 9의 동적 경로는 **[Vercel](https://vercel.com/)에서 자동으로 구성**되며, `vercel.json` 추가 설정이 필요하지 않습니다. -You can read more about [Dynamic Routing here](/docs/pages/building-your-application/routing/dynamic-routes). +자세한 내용은 [Dynamic Routing here](/docs/pages/building-your-application/routing/dynamic-routes)에서 확인할 수 있습니다. ## Check your Custom App File (`pages/_app.js`) -If you previously copied the [Custom ``](/docs/pages/building-your-application/routing/custom-app) example, you may be able to remove your `getInitialProps`. +과거에 [Custom ``](/docs/pages/building-your-application/routing/custom-app) 예제를 복사한 경험이 있는 경우, `getInitialProps`를 제거할 수 있습니다. -Removing `getInitialProps` from `pages/_app.js` (when possible) is important to leverage new Next.js features! +새로운 Next.js 기능을 활용하기 위해 `pages/_app.js`에서 `getInitialProps`을 제거해 주세요! -The following `getInitialProps` does nothing and may be removed: +`getInitialProps`는 아무 작업도 하지 않으므로 제거해도 됩니다: ```js class MyApp extends App { - // Remove me, I do nothing! + // 삭제해 주세요, 아무것도 수행하지 않습니다! static async getInitialProps({ Component, ctx }) { let pageProps = {} @@ -67,17 +65,17 @@ class MyApp extends App { ### `@zeit/next-typescript` is no longer necessary -Next.js will now ignore usage `@zeit/next-typescript` and warn you to remove it. Please remove this plugin from your `next.config.js`. +Next.js는 이제 `@zeit/next-typescript` 사용을 무시하고 이를 제거하라는 경고를 표시할 겁니다. 이 플러그인을 `next.config.js`에서 제거하세요. -Remove references to `@zeit/next-typescript/babel` from your custom `.babelrc` (if present). +커스텀 `.babelrc`에 `@zeit/next-typescript/babel` 참조가 있는 경우 이를 제거하세요. -The usage of [`fork-ts-checker-webpack-plugin`](https://github.com/Realytics/fork-ts-checker-webpack-plugin/issues) should also be removed from your `next.config.js`. +[`fork-ts-checker-webpack-plugin`](https://github.com/Realytics/fork-ts-checker-webpack-plugin/issues) 사용도 `next.config.js`에서 제거해야 합니다. -TypeScript Definitions are published with the `next` package, so you need to uninstall `@types/next` as they would conflict. +TypeScript 정의 파일은 next 패키지에 포함되어 있으므로, 충돌을 방지하기 위해 @types/next를 제거해야 합니다. -The following types are different: +다음 유형은 다릅니다: -> This list was created by the community to help you upgrade, if you find other differences please send a pull-request to this list to help other users. +> 이 목록은 업그레이드를 돕기 위해 커뮤니티가 작성한 것입니다. 차이점을 발견한다면, 이 목록에 pull-request를 보내어 다른 사용자들을 도와주세요. From: @@ -97,14 +95,14 @@ import { DocumentContext, DocumentInitialProps } from 'next/document' ### The `config` key is now an export on a page -You may no longer export a custom variable named `config` from a page (i.e. `export { config }` / `export const config ...`). -This exported variable is now used to specify page-level Next.js configuration like Opt-in AMP and API Route features. +페이지에서 `config`라는 이름의 사용자 지정 변수를 더 이상 내보낼 수 없습니다. (예. `export { config }` / `export const config ...`) +내보낸 변수는 이제 Opt-in AMP 및 API Route 기능과 같은 페이지 수준의 Next.js 구성을 지정하는 데 사용됩니다. -You must rename a non-Next.js-purposed `config` export to something different. +Next.js와 관련 없는 config 내보내기 변수는 다른 이름으로 변경해야 합니다. ### `next/dynamic` no longer renders "loading..." by default while loading -Dynamic components will not render anything by default while loading. You can still customize this behavior by setting the `loading` property: +동적 컴포넌트는 로딩 중에 기본적으로 아무것도 렌더링하지 않습니다. `loading` 속성을 설정하여 이 동작을 계속 사용자 지정할 수 있습니다: ```jsx import dynamic from 'next/dynamic' @@ -119,15 +117,15 @@ const DynamicComponentWithCustomLoading = dynamic( ### `withAmp` has been removed in favor of an exported configuration object -Next.js now has the concept of page-level configuration, so the `withAmp` higher-order component has been removed for consistency. +Next.js에서 page-level configuration 개념을 도입했기 때문에 일관성을 위해 `withAmp` 고차 컴포넌트를 제거했습니다. -This change can be **automatically migrated by running the following commands in the root of your Next.js project:** +해당 변경 사항은 **아래 명령어를 Next.js 프로젝트의 루트에서 실행하여 자동으로 마이그레이션할 수 있습니다:** ```bash filename="Terminal" curl -L https://github.com/vercel/next-codemod/archive/master.tar.gz | tar -xz --strip=2 next-codemod-master/transforms/withamp-to-config.js npx jscodeshift -t ./withamp-to-config.js pages/**/*.js ``` -To perform this migration by hand, or view what the codemod will produce, see below: +마이그레이션을 수동으로 수행하거나, codemod의 생성 결과를 보려면 아래를 참조하세요: **Before** @@ -159,9 +157,9 @@ export const config = { ### `next export` no longer exports pages as `index.html` -Previously, exporting `pages/about.js` would result in `out/about/index.html`. This behavior has been changed to result in `out/about.html`. +과거, pages/about.js를 내보내면 out/about/index.html이 생성되었습니다. 이 행위는 `out/about.html`이 생성되는 결과로 바뀌었습니다. -You can revert to the previous behavior by creating a `next.config.js` with the following content: +동작을 되돌리려면 다음 내용을 포함하는 `next.config.js` 파일을 생성하세요: ```js filename="next.config.js" module.exports = { @@ -171,16 +169,16 @@ module.exports = { ### `pages/api/` is treated differently -Pages in `pages/api/` are now considered [API Routes](https://nextjs.org/blog/next-9#api-routes). -Pages in this directory will no longer contain a client-side bundle. +`pages/api/`의 페이지는 이제 [API Routes](https://nextjs.org/blog/next-9#api-routes)로 간주됩니다. +해당 경로에 있는 페이지는 더 이상 클라이언트 측 번들을 포함하지 않습니다. ## Deprecated Features ### `next/dynamic` has deprecated loading multiple modules at once -The ability to load multiple modules at once has been deprecated in `next/dynamic` to be closer to React's implementation (`React.lazy` and `Suspense`). +`next/dynamic`에서 여러 모듈을 한 번에 로드하는 기능을 사용하지 않게 되어 React(`React.lazy` and `Suspense`) 구현에 더 가까워졌습니다. -Updating code that relies on this behavior is relatively straightforward! We've provided an example of a before/after to help you migrate your application: +동작에 의존하는 코드를 업데이트하는 것은 비교적 간단합니다! 애플리케이션을 마이그레이션하는 데 도움이 되는 예제를 참고해 주세요: **Before** diff --git a/pages/index.mdx b/pages/index.mdx index 0960dbf..ac0cab5 100644 --- a/pages/index.mdx +++ b/pages/index.mdx @@ -421,6 +421,144 @@ Next.js 공식 문서 한글 번역 프로젝트입니다. by [@luciancah](https 🖋 + + + Yoon Han Bin +
    + + Yoon Han Bin + +
    +
    + + 🖋 + + + + + 조민수 +
    + + 조민수 + +
    +
    + + 🖋 + + + + + HyojinLee +
    + + HyojinLee + +
    +
    + + 🖋 + + + + + vinnie +
    + + vinnie + +
    +
    + + 🖋 + + + + + Arin +
    + + Arin + +
    +
    + + 🖋 + + + + + + + Jinseung +
    + + Jinseung + +
    +
    + + 🖋 + + + + + Hyunsoo Kim +
    + + Hyunsoo Kim + +
    +
    + + 🖋 + + + + + 박우빈 +
    + + 박우빈 + +
    +
    + + 🖋 + +