Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
352 changes: 267 additions & 85 deletions src/content/docs/ko/guides/fonts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,125 +6,307 @@ description: Astro 웹사이트에 사용자 정의 서체를 추가하려고
i18nReady: true
---
import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro';
import { Steps } from '@astrojs/starlight/components'
import ReadMore from '~/components/ReadMore.astro';
import { Steps, Tabs, TabItem } from '@astrojs/starlight/components';

이 안내서는 프로젝트에 웹 글꼴을 추가하고 컴포넌트에서 사용하는 방법을 설명합니다.
이 안내서는 프로젝트에 [웹 글꼴](https://developer.mozilla.org/ko/docs/Learn_web_development/Core/Text_styling/Web_fonts)을 추가하고 컴포넌트에서 사용하는 방법을 설명합니다.

## 로컬 글꼴 파일 사용
Astro는 통합되고, [완전히 사용자 정의 가능하며](/ko/reference/configuration-reference/), 타입 안정성을 갖춘 API를 통해 파일 시스템 및 다양한 글꼴 제공업체(예: Fontsource, Google)의 글꼴을 사용할 수 있는 방법을 제공합니다.

이 예시는 `DistantGalaxy.woff` 글꼴 파일을 사용하여 사용자 정의 글꼴을 추가하는 방법을 보여줍니다.
웹 글꼴은 로드 시간과 렌더링 시간 모두에서 페이지 성능에 영향을 미칠 수 있습니다. 이 API는 프리로드 링크, 최적화된 대체 글꼴, 정해진 기본값 등 자동 [웹 글꼴 최적화](https://web.dev/learn/performance/optimize-web-fonts)를 통해 사이트 성능을 유지하는 데 도움을 줍니다. [일반적인 사용 예시를 참조하세요](#예시).

폰트 API는 글꼴을 다운로드하고 캐시하여 사이트에서 제공함으로써 성능과 개인 정보 보호에 중점을 둡니다. 이를 통해 사용자 데이터를 서드파티 사이트로 전송하는 것을 방지하고, 모든 방문자에게 일관된 글꼴 세트를 제공할 수 있습니다.

## 사용자 정의 글꼴 구성

Astro 프로젝트에 사용자 정의 글꼴을 등록하는 것은 Astro 구성 파일의 [`fonts` 옵션](/ko/reference/configuration-reference/)을 통해 이루어집니다.

사용하려는 각 글꼴에 대해 [이름](/ko/reference/configuration-reference/), [CSS 변수](/ko/reference/configuration-reference/), 그리고 Astro 글꼴 제공업체를 지정해야 합니다.

Astro는 Adobe, Bunny, Fontshare, Fontsource, Google, Google Icons, NPM과 같은 [가장 인기 있는 글꼴 제공업체에 대한 내장 지원](/ko/reference/font-provider-reference/#built-in-providers)과 로컬 글꼴 파일 사용을 지원합니다. 또한 성능과 방문자 경험을 최적화하기 위해 [글꼴 구성을 추가로 사용자 정의할 수 있습니다](#세부적인-글꼴-구성).


### 로컬 글꼴 파일 사용

이 예시는 `DistantGalaxy.woff2` 글꼴 파일을 사용하여 사용자 정의 글꼴을 추가하는 방법을 보여줍니다.

<Steps>
1. `public/fonts/` 디렉터리에 글꼴 파일을 추가하세요.
2. CSS에 다음 `@font-face` 문을 추가하세요. CSS는 전역 `.css` 파일이거나, `<style is:global>` 블록이거나, 글꼴을 사용할 특정 레이아웃이나 컴포넌트의 `<style>` 블록일 수도 있습니다.

```css
/* 사용자 정의 글꼴 모음을 등록하고 브라우저에 해당 글꼴 모음을 찾을 수 있는 위치를 알려주세요. */
@font-face {
font-family: 'DistantGalaxy';
src: url('/fonts/DistantGalaxy.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}

1. 글꼴 파일을 [`src/` 디렉터리](/ko/basics/project-structure/#src) 안에 추가합니다. 예를 들어 `src/assets/fonts/`와 같이 추가할 수 있습니다.

2. Astro 설정 파일에서 [로컬 글꼴 제공업체](/ko/reference/font-provider-reference/#local)를 사용하여 새 글꼴 패밀리를 만들고 포함할 변형을 지정합니다.

```js title="astro.config.mjs"
import { defineConfig, fontProviders } from "astro/config";

export default defineConfig({
fonts: [{
provider: fontProviders.local(),
name: "DistantGalaxy",
cssVariable: "--font-distant-galaxy",
options: {
variants: [{
src: ['./src/assets/fonts/DistantGalaxy.woff2'],
weight: 'normal',
style: 'normal'
}]
}
}]
});
```
3. 이제 글꼴이 구성되었으며 프로젝트에서 사용할 수 있도록 [페이지 헤드에 추가](#사용자-정의-글꼴-적용)할 준비가 되었습니다.

3. `@font-face` 문의 `font-family` 값을 사용하여 컴포넌트나 레이아웃의 요소에 스타일을 지정하세요. 이 예시에서 `<h1>` 제목에는 사용자 정의 글꼴이 적용되지만 `<p>` 단락에는 적용되지 않습니다.
</Steps>

```astro title="src/pages/example.astro" {9-11}
---
---
### Fontsource 사용

<h1>머나먼 은하계에서...</h1>
Astro는 Google Fonts 및 기타 오픈 소스 글꼴 사용을 간소화하는 [Fontsource](https://fontsource.org/) 지원을 포함하여 [여러 글꼴 제공업체](/ko/reference/font-provider-reference/#built-in-providers)를 기본으로 지원합니다.

<p>사용자 정의 글꼴을 사용해 제목을 멋지게 꾸밀 수 있습니다!</p>
다음 예시에서는 Fontsource를 사용하여 사용자 정의 글꼴 지원을 추가하는 방법을 보여주지만, Astro의 내장 글꼴 제공업체(예: [Adobe](https://fonts.adobe.com/), [Bunny](https://fonts.bunny.net/))에서도 과정은 비슷합니다.

<style>
h1 {
font-family: 'DistantGalaxy', sans-serif;
}
</style>
<Steps>

1. [Fontsource의 카탈로그](https://fontsource.org/)에서 사용하고 싶은 글꼴을 찾으세요. 이 예시에서는 [Roboto](https://fontsource.org/fonts/roboto)를 사용합니다.

2. Astro 설정 파일에서 [Fontsource 제공업체](/ko/reference/font-provider-reference/#fontsource)를 사용하여 새로운 글꼴 패밀리를 만듭니다.

```js title="astro.config.mjs"
import { defineConfig, fontProviders } from "astro/config";

export default defineConfig({
fonts: [{
provider: fontProviders.fontsource(),
name: "Roboto",
cssVariable: "--font-roboto",
}]
});
```
3. 이제 글꼴이 구성되었으며 프로젝트에서 사용할 수 있도록 [페이지 헤드에 추가](#사용자-정의-글꼴-적용)할 준비가 되었습니다.

</Steps>

## Fontsource 사용
## 사용자 정의 글꼴 적용

[Fontsource](https://fontsource.org/) 프로젝트는 Google Fonts 및 기타 오픈 소스 글꼴 사용을 단순화합니다. 사용하려는 글꼴을 설치할 수 있는 npm 모듈을 제공합니다.
[글꼴이 구성된](#사용자-정의-글꼴-구성) 후에는 식별 CSS 변수와 함께 페이지 헤드에 추가해야 합니다. 그런 다음, 이 변수를 사용하여 페이지 스타일을 정의할 수 있습니다.

<Steps>
1. [Fontsource 카탈로그](https://fontsource.org/)에서 사용하고 싶은 글꼴을 찾아보세요. 이 예시에서는 [Twinkle Star](https://fontsource.org/fonts/twinkle-star)를 사용합니다.
2. 선택한 글꼴에 대한 패키지를 설치합니다.

<PackageManagerTabs>
<Fragment slot="npm">
```shell
npm install @fontsource/twinkle-star
```
</Fragment>
<Fragment slot="pnpm">
```shell
pnpm add @fontsource/twinkle-star
```
</Fragment>
<Fragment slot="yarn">
```shell
yarn add @fontsource/twinkle-star
```
</Fragment>
</PackageManagerTabs>

:::tip
Fontsource 웹사이트의 각 글꼴 페이지에 있는 "Quick Installation" 섹션에서 올바른 패키지 이름을 찾을 수 있습니다. 패키지 이름은 `@fontsource/` 또는 `@fontsource-variable/`로 시작하고 그 뒤에 글꼴 이름이 있습니다.
:::

3. 글꼴을 사용하려는 컴포넌트에서 글꼴 패키지를 가져옵니다. 일반적으로 사이트 전체에서 글꼴을 사용할 수 있도록 공통 레이아웃 컴포넌트에서 이 작업을 수행할 수 있습니다.

가져오기는 글꼴을 설정하는 데 필요한 `@font-face` 규칙을 자동으로 추가합니다.

```astro title="src/layouts/BaseLayout.astro"

1. 필요한 `cssVariable` 속성을 가진 [`<Font />`](/ko/reference/modules/astro-assets/) 컴포넌트를 페이지 헤드에 가져와 포함합니다. 일반적으로 전용 `Head.astro` 컴포넌트나 [레이아웃](/ko/basics/layouts/) 컴포넌트에 직접 포함합니다.

```astro title="src/layouts/Layout.astro" ins={2,7}
---
import '@fontsource/twinkle-star';
import { Font } from "astro:assets";
---

<html>
<head>
<Font cssVariable="--font-distant-galaxy" />
</head>
<body>
<slot />
</body>
</html>
```

4. Fontsource 페이지의 `body` 예시에 나와있는 것처럼 `font-family` 값으로 글꼴의 이름을 사용하세요. 이는 Astro 프로젝트에서 CSS를 작성할있는 모든 곳에서 작동합니다.
2. 해당 레이아웃으로 렌더링되는 모든 페이지(레이아웃 컴포넌트 자체 포함)에서 이제 글꼴의 `cssVariable`로 스타일을 정의하여 사용자 정의 글꼴을 적용할있습니다.

```css
h1 {
font-family: "Twinkle Star", cursive;
}
다음 예시에서는 `<h1>` 제목에 사용자 정의 글꼴이 적용되지만, 단락 `<p>`에는 적용되지 않습니다.

```astro title="src/pages/example.astro" ins={10-12}
---
import Layout from "../layouts/Layout.astro";
---
<Layout>
<h1>In a galaxy far, far away...</h1>

<p>Custom fonts make my headings much cooler!</p>

<style>
h1 {
font-family: var(--font-distant-galaxy);
}
</style>
</Layout>
```
</Steps>

웹사이트의 렌더링 시간을 최적화하기 위해 초기 페이지 표시에 필요한 글꼴을 미리 로드할 수 있습니다.
자세한 내용과 사용법은 [글꼴 사전 로드에 대한 Fontsource 가이드](https://fontsource.org/docs/getting-started/preload)를 참조하세요.
</Steps>

## Tailwind에 글꼴 등록

[Tailwind](/ko/guides/styling/#tailwind)를 사용하는 경우 이 페이지의 이전 방법 중 하나에 약간의 수정을 거쳐 글꼴을 설치할 수 있습니다. [로컬 글꼴에 대한 `@font-face` 문](#로컬-글꼴-파일-사용)을 추가하거나 [Fontsource의 `import` 전략](#fontsource-사용)을 사용하여 글꼴을 설치할 수 있습니다.
[Tailwind](/ko/guides/styling/#tailwind)를 사용하여 스타일링하는 경우, `font-face` CSS 속성으로 스타일을 적용하지 않습니다.

Tailwind에 글꼴을 등록하려면 다음 단계를 따르세요.
대신, [사용자 정의 글꼴을 구성](#사용자-정의-글꼴-구성)하고 [페이지 헤드에 추가](#사용자-정의-글꼴-적용)한 후에는 Tailwind 구성을 업데이트하여 글꼴을 등록해야 합니다.

<Steps>
1. 위 안내 중 하나를 따르되, CSS에 `font-family`를 추가하는 마지막 단계는 건너뛰세요.
2. `src/styles/global.css`에 서체 이름을 추가하세요.
<Tabs>

<TabItem label="Tailwind CSS 4.0">

이 예시에서는 `Inter`를 sans-serif 글꼴 스택에 추가합니다.
```css title="src/styles/global.css" ins={4} ins="inline"
@import "tailwindcss";

```css title="src/styles/global.css" ins={3-5}
@import 'tailwindcss';

@theme {
--font-sans: 'Inter', 'sans-serif';
@theme inline {
--font-sans: var(--font-roboto);
}
```

이제 프로젝트의 모든 sans-serif 글자 (Tailwind의 기본값)는 선택한 글꼴을 사용하고 `font-sans` 클래스도 Inter 글꼴을 적용합니다.
</Steps>
</TabItem>

<TabItem label="Tailwind CSS 3.0">

```js title="tailwind.config.mjs" ins={6-8}
/** @type {import("tailwindcss").Config} */
export default {
content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
theme: {
extend: {},
fontFamily: {
sans: ["var(--font-roboto)"]
}
},
plugins: []
};
```

</TabItem>

</Tabs>

자세한 내용은 [사용자 정의 글꼴 모음 추가에 대한 Tailwind 문서](https://tailwindcss.com/docs/font-family#using-a-custom-value)를 확인하세요.

## 프로그래밍 방식으로 글꼴 데이터 접근

[`fontData`](/ko/reference/modules/astro-assets/) 객체를 사용하면 하위 수준의 글꼴 패밀리 데이터를 프로그래밍 방식으로 가져올 수 있습니다. 예를 들어, 적절한 [형식](/ko/reference/configuration-reference/) 구성과 결합하여 [satori](https://github.com/vercel/satori)를 사용하여 OpenGraph 이미지를 생성하기 위한 [API 라우트](/ko/guides/endpoints/#서버-엔드포인트-api-라우트)에서 사용할 수 있습니다:

자세한 내용은 [사용자 정의 글꼴 모음 추가에 대한 Tailwind 문서](https://tailwindcss.com/docs/font-family#using-custom-values)를 확인하세요.
```tsx title="src/pages/og.png.ts" {2} "fontData[\"--font-roboto\"]"
import type{ APIRoute } from "astro";
import { fontData } from "astro:assets";
import satori from "satori";
import { html } from "satori-html";

## 더 많은 자료
export const GET: APIRoute = async (context) => {
const data = fontData["--font-roboto"];

- [MDN의 웹 글꼴 안내서](https://developer.mozilla.org/ko/docs/Learn/CSS/Styling_text/Web_fonts)에서 웹 글꼴이 작동하는 방식을 알아보세요.
- [Font Squirrel의 웹 글꼴 생성기](https://www.fontsquirrel.com/tools/webfont-generator)를 사용하여 글꼴에 맞는 CSS를 생성하세요.
const svg = await satori(
html`<div style="color: black;">hello, world</div>`,
{
width: 600,
height: 400,
fonts: [
{
name: "Roboto",
data: await fetch(
new URL(data[0].src[0].url, context.url.origin),
).then((res) => res.arrayBuffer()),
weight: 400,
style: "normal",
},
],
},
);

// ...
}
```

## 세부적인 글꼴 구성

글꼴 패밀리는 굵기 및 스타일과 같은 속성(예: `weights: [500, 600]` 및 `styles: ["normal", "bold"]`)의 조합으로 정의되지만, 이 중 특정 조합만 다운로드하고 싶을 수 있습니다.

다운로드할 글꼴 파일을 더 세부적으로 제어하려면, 동일한 글꼴(즉, 동일한 `cssVariable`, `name`, `provider` 속성)을 다른 조합으로 여러 번 지정할 수 있습니다. Astro는 결과를 병합하고 필요한 파일만 다운로드합니다. 예를 들어, 일반 `500`과 `600`을 다운로드하면서 이탤릭 `500`만 다운로드하는 것이 가능합니다.

```js title="astro.config.mjs"
import { defineConfig, fontProviders } from "astro/config";

export default defineConfig({
fonts: [
{
name: "Roboto",
cssVariable: "--roboto",
provider: fontProviders.google(),
weights: [500, 600],
styles: ["normal"]
},
{
name: "Roboto",
cssVariable: "--roboto",
provider: fontProviders.google(),
weights: [500],
styles: ["italic"]
}
]
});
```

## 캐싱

폰트 API의 캐싱 구현은 개발 환경에서는 실용적이고 프로덕션 환경에서는 효율적이도록 설계되었습니다. 빌드 중에는 폰트 파일이 `_astro/fonts` 출력 디렉터리로 복사되어 정적 자산의 HTTP 캐싱(일반적으로 1년) 혜택을 받을 수 있습니다.

개발 환경에서 캐시를 지우려면 `.astro/fonts` 디렉터리를 제거하세요. 빌드 캐시를 지우려면 `node_modules/.astro/fonts` 디렉터리를 제거하세요.

## 예시

Astro의 폰트 기능은 유연한 구성 옵션을 기반으로 합니다. 프로젝트의 폰트 구성은 단순화된 예시와 다를 수 있으므로, 프로덕션 환경에서 다양한 폰트 구성이 어떻게 보이는지 보여주기 위해 다음 예시가 제공됩니다.

```js title="astro.config.mjs"
import { defineConfig, fontProviders } from "astro/config";

export default defineConfig({
fonts: [
{
name: "Roboto",
cssVariable: "--font-roboto",
provider: fontProviders.google(),
// 기본 포함:
// weights: [400] ,
// styles: ["normal", "italic"],
// subsets: ["latin"],
// fallbacks: ["sans-serif"],
// formats: ["woff2"],
},
{
name: "Inter",
cssVariable: "--font-inter",
provider: fontProviders.fontsource(),
// 실제로 사용되는 굵기를 지정합니다.
weights: [400, 500, 600, 700],
// 실제로 사용되는 스타일을 지정합니다.
styles: ["normal"],
// 페이지에서 사용되는 문자 전용 글꼴 파일만 다운로드합니다.
subsets: ["latin", "cyrillic"],
// 더 많은 글꼴 형식을 다운로드합니다.
formats: ["woff2", "woff"],
},
{
name: "JetBrains Mono",
cssVariable: "--font-jetbrains-mono",
provider: fontProviders.fontsource(),
// 페이지에서 사용되는 문자 전용 글꼴 파일만 다운로드합니다.
subsets: ["latin", "latin-ext"],
// 의도한 모양과 일치하는 대체 글꼴 패밀리를 사용합니다.
fallbacks: ["monospace"],
},
{
name: "Poppins",
cssVariable: "--font-poppins",
provider: fontProviders.local(),
options: {
// 굵기와 스타일이 지정되지 않았으므로
// Astro가 각 변형에 대해 이를 추론하려고 시도합니다.
variants: [
{
src: [
"./src/assets/fonts/Poppins-regular.woff2",
"./src/assets/fonts/Poppins-regular.woff",
]
},
{
src: [
"./src/assets/fonts/Poppins-bold.woff2",
"./src/assets/fonts/Poppins-bold.woff",
]
},
]
}
}
],
});
Loading