본문으로 건너뛰기

그림과 글꼴

Next.js 목차 화면 다듬기 레슨 34 / 47

목차

next/image의 <Image>는 <img>를 그려 주는 컴포넌트로, 그릴 크기 width · height와 대신 글 alt를 꼭 받습니다. next/font는 글꼴 파일을 받아 두었다가 내 앱의 주소에서 보내 줍니다. 이 레슨은 루트 레이아웃의 바닥글에 템플릿의 그림 next.svg를 넣고, 앱 전체에 한국어 글꼴 Noto Sans KR을 걸어 받은 HTML과 브라우저에서 확인합니다.

그림 넣기 img에서는 img에 width · height를 적어, 그림을 받는 동안 비워 둘 자리를 잡았습니다. 빠뜨려도 브라우저는 말없이 그립니다. 글꼴은 바깥 글꼴 서버의 주소를 걸면, 쪽을 열 때마다 브라우저가 그 서버에 글꼴을 달라고 합니다. next/image와 next/font는 이 둘을 Next.js가 맡게 합니다.

1Image로 그림 넣기

루트 app/layout.tsx에서 next/image의 Image를 가져와, 바닥글에 Next.js 글자 그림 public/next.svg를 넣습니다. 이 앱을 만든 도구의 표시입니다. 검은 글자라, 컴퓨터를 어두운 화면으로 쓰면 바탕에 묻혀 잘 안 보입니다. 그때는 받은 HTML의 <img>로 확인합니다.

app/layout.tsx
…
import Image from 'next/image';
…
        <footer>
          바닥글
          <Image
            src="/next.svg"
            alt="Next.js"
            width={100}
            height={20}
          />
        </footer>
…
  • src는 public/ 안 파일의 주소입니다. public/next.svg는 /next.svg입니다(프로젝트 파일 읽기).
  • width · height는 그릴 크기(픽셀)입니다. 받은 <img>에 그대로 붙어, 브라우저가 그림을 받기 전에 자리를 잡습니다.
  • alt는 그림 대신 쓸 글입니다(alt 제대로 쓰기).
app/layout.tsx 전체 · 받은 HTML

아래는 그림을 넣은 루트 레이아웃과, 저장한 뒤 /stats를 연 받은 HTML(다듬음)입니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
import Image from 'next/image';
import './globals.css';
import TabBar from
  '@/components/TabBar';

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body>
        <TabBar />
        {children}
        <footer>
          바닥글
          <Image
            src="/next.svg"
            alt="Next.js"
            width={100}
            height={20}
          />
        </footer>
      </body>
    </html>
  );
}

export default RootLayout;
HTML
<nav>
<a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a>
</nav>
<h1>통계</h1>
<template id="B:0">
</template>
<p>세는 중</p>
<footer>바닥글<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"/>
</footer>
<div hidden id="S:0">
<p>모두 4개</p>
</div>
결과 화면

받은 <img>에는 적은 alt · width · height에 더해 loading="lazy"와 decoding="async"가 붙었습니다. loading="lazy"는 그림이 화면 가까이 올 때 받으라는 뜻입니다. src는 적은 /next.svg 그대로입니다. SVG 그림은 줄일 것이 없어 그대로 보내기 때문입니다. PNG · JPG 같은 그림이면 src · srcset이 줄인 그림의 주소 /_next/image?url=…가 됩니다. 이 레슨처럼 width를 적으면 srcset에는 화면 밀도에 맞춘 두 크기(1x · 2x)가 들어갑니다(Next.js 문서 Image).

2next/font로 글꼴 걸기

같은 app/layout.tsx에서 next/font/google의 Noto_Sans_KR을 불러, 돌려받은 클래스 이름을 <body>에 겁니다.

app/layout.tsx
…
import {
  Noto_Sans_KR,
} from 'next/font/google';
…
const noto = Noto_Sans_KR({
  subsets: ['latin'],
});
…
      <body
        className={
          noto.className
        }
      >
…
  • 함수 이름은 Google Fonts의 글꼴 이름을 밑줄로 이은 것입니다(Noto Sans KR → Noto_Sans_KR).
  • 부르면 이 글꼴을 거는 클래스 이름 noto.className을 돌려줍니다.
  • subsets는 쪽을 열 때 미리 받아 둘 글자 묶음입니다. Next.js가 아는 Noto Sans KR의 묶음은 cyrillic · latin · latin-ext · vietnamese뿐이라 latin을 적습니다. 한글 글꼴 파일은 쪽에 한글이 나오면 그 글자가 든 조각만 따로 받습니다.
app/layout.tsx 전체 · 받은 HTML 그대로

아래는 글꼴을 건 루트 레이아웃과, 저장한 뒤 /stats를 연 받은 HTML입니다. script · 주석 · style 속성과 <body> 맨 앞의 빈 <div hidden>을 뺐습니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
import Image from 'next/image';
import {
  Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
  '@/components/TabBar';

const noto = Noto_Sans_KR({
  subsets: ['latin'],
});

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body
        className={
          noto.className
        }
      >
        <TabBar />
        {children}
        <footer>
          바닥글
          <Image
            src="/next.svg"
            alt="Next.js"
            width={100}
            height={20}
          />
        </footer>
      </body>
    </html>
  );
}

export default RootLayout;
HTML
<html lang="ko">
<head>
<meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="/_next/static/chunks/%5Broot-of-the-server%5D__0elsnlzclbi0j._.css" data-precedence="next_static/chunks/[root-of-the-server]__0elsnlzclbi0j._.css"/>
<link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/%5Bturbopack%5D_browser_dev_hmr-client_hmr-client_ts_0oc3hfxhoz2c3._.js"/>
<title>통계 · 레시피 보관함</title>
<meta name="description" content="내 레시피를 모아 두는 곳"/>
<link rel="icon" href="/favicon.ico?favicon.117ezoe8m31dk.ico" sizes="48x48" type="image/x-icon"/>
<meta name="next-size-adjust" content=""/>
</head>
<body class="noto_sans_kr_d805734-module__HYGTbq__className">
<nav>
<a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a>
</nav>
<h1>통계</h1>
<template id="B:0">
</template>
<p>세는 중</p>
<footer>바닥글<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"/>
</footer>
<div hidden id="S:0">
<p>모두 4개</p>
</div>
</body>
</html>
결과 화면탭: 통계 · 레시피 보관함

저장하고 /stats를 새로 고치면 글자 모양이 Noto Sans KR로 바뀝니다. 차이가 작아, 줄 사이가 조금 넓어지고 한글이 조금 둥글어진 것을 Ctrl과 +(맥은 Cmd와 +)로 키워 견주면 보입니다. 위 접기의 받은 HTML에서 <body>의 class가 noto_sans_kr_로 시작하는 이름입니다. 그 이름이 noto.className의 값입니다.

개발자 도구 Network 판에서 글꼴 파일(.woff2)을 보면, 모두 내 앱의 주소 /_next/static/media/…⁠에서 왔습니다. next/font가 Google Fonts의 글꼴 파일을 받아 내 앱의 파일로 두었기 때문입니다. 브라우저는 Google에 요청하지 않습니다(Next.js 문서 Font — 'No requests are sent to Google by the browser').

글꼴 파일은 개발 서버나 빌드가 처음 쓸 때 Google Fonts에서 받아 둡니다. 그래서 그때는 인터넷이 이어져 있어야 합니다. 받지 못하면 개발 서버는 Failed to download로 시작하는 경고를 찍고 대체 글꼴로 그립니다. 빌드는 Failed to fetch로 시작하는 오류로 멈춥니다.

<body>에 건 까닭이 있습니다. Next.js 문서의 예는 <html>에 클래스를 겁니다. 이 앱에서 그렇게 하면 글자가 바뀌지 않습니다. 템플릿의 app/globals.css에 body의 font-family 규칙이 있어, <html>에서 물려받은 글꼴 대신 body에 바로 건 그 규칙이 쓰이기 때문입니다(물려받기). <body>에 건 클래스 규칙은 태그 이름 body로 고른 규칙보다 세서 이깁니다. 클래스로 고른 규칙이 태그 이름으로 고른 규칙보다 센 것을 명시도라 합니다(명시도).

해 보기 — alt를 지우고 린트 · 빌드 돌리기

alt를 빠뜨리면 어디서 알려 줄까요? <Image>에서 alt="Next.js" 줄을 지우고 저장한 뒤, 개발 서버를 Ctrl+C로 끄고 npm run lint와 npm run build를 차례로 돌립니다.

alt를 지운 app/layout.tsx · 린트 · 빌드

아래는 alt 줄을 지운 루트 레이아웃, 린트와 빌드 출력입니다. 린트의 파일 자리는 내 컴퓨터의 폴더로 찍히고, 시간은 다를 수 있습니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
import Image from 'next/image';
import {
  Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
  '@/components/TabBar';

const noto = Noto_Sans_KR({
  subsets: ['latin'],
});

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body
        className={
          noto.className
        }
      >
        <TabBar />
        {children}
        <footer>
          바닥글
          <Image
            src="/next.svg"
            width={100}
            height={20}
          />
        </footer>
      </body>
    </html>
  );
}

export default RootLayout;
> recipe-box-next@0.1.0 lint
> eslint


~/recipe-box-next/app/layout.tsx
  41:11  warning  Image elements must have an alt prop, either with meaningful text, or an empty string for decorative images  jsx-a11y/alt-text

✖ 1 problem (0 errors, 1 warning)
  Creating an optimized production build ...
✓ Compiled successfully in 1930ms
  Running TypeScript ...
app/layout.tsx(41,12): error TS2741: Property 'alt' is missing in type '{ src: string; width: number; height: number; }' but required in type '{ src: string | StaticImport; alt: string; width?: number | `${number}` | undefined; height?: number | `${number}` | undefined; fill?: boolean | undefined; loader?: ImageLoader | undefined; ... 13 more ...; lazyRoot?: string | undefined; }'.
Failed to type check.
exit=1

개발 서버를 끄기 전에 쪽을 새로 고쳤다면, 서버 터미널에 [browser] Image is missing⁠으로 시작해 alt가 없다고 알리는 줄이 찍혔습니다. 린트는 jsx-a11y/alt-text 규칙으로 경고만 하고 끝납니다. 빌드는 타입 검사에서 멈춥니다. Image의 타입이 alt를 꼭 받는 속성으로 정해 두었기 때문입니다. 그림이 뜻 없는 꾸밈이면 alt=""로 빈 글을 적습니다(alt 제대로 쓰기).

다 봤으면 지운 alt="Next.js" 줄을 되살려 저장하고, npm run dev로 개발 서버를 다시 띄웁니다.

예제

width를 빠뜨리면 어떻게 될까요? 개발 서버를 켜 둔 채 <Image>에서 width={100} 줄을 지우고 저장한 뒤 /stats를 새로 고칩니다. 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 그림 파일의 크기로 그린다
  • ② 쪽이 500이 되고, global-error.tsx의 화면이 뜬다
  • ③ width 없는 <img>로 그린다
결과 보기

②입니다. 아래는 2절 그대로의 루트 레이아웃, width를 지운 판, /stats의 응답 머리와 서버 터미널, 브라우저 화면입니다. 시간과 digest 뒤의 수는 다를 수 있습니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
import Image from 'next/image';
import {
  Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
  '@/components/TabBar';

const noto = Noto_Sans_KR({
  subsets: ['latin'],
});

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body
        className={
          noto.className
        }
      >
        <TabBar />
        {children}
        <footer>
          바닥글
          <Image
            src="/next.svg"
            alt="Next.js"
            width={100}
            height={20}
          />
        </footer>
      </body>
    </html>
  );
}

export default RootLayout;
app/layout.tsx
import type {
  Metadata,
} from 'next';
import Image from 'next/image';
import {
  Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
  '@/components/TabBar';

const noto = Noto_Sans_KR({
  subsets: ['latin'],
});

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body
        className={
          noto.className
        }
      >
        <TabBar />
        {children}
        <footer>
          바닥글
          <Image
            src="/next.svg"
            alt="Next.js"
            height={20}
          />
        </footer>
      </body>
    </html>
  );
}

export default RootLayout;
HTTP/1.1 500 Internal Server Error
Cache-Control: no-store
Content-Type: text/html; charset=utf-8
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 212ms
✓ Running next.config.ts took 1014ms
- Cache Components enabled
- Partial Prefetching enabled

⨯ Error: Image with src "/next.svg" is missing required "width" property.
    at ignore-listed frames {
  digest: '4069232475'
}
레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /stats 500 in 175ms (next.js: 59ms, application-code: 117ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
<h1>앱을 못 그렸습니다</h1>
<button>다시</button>
결과 화면

<Image>는 개발 판에서 받은 속성을 검사합니다. width가 없으면 Image with src "/next.svg"⁠로 시작해 width가 없다고 알리는 오류를 던집니다. 그림이 루트 레이아웃에 있어, 그 오류는 오류 화면 3절처럼 global-error.tsx가 받았습니다. 브라우저에는 이 오류 글을 담은 오류 판이 그 위에 먼저 뜹니다. width는 해 보기 빌드 상자의 타입에서 물음표가 붙은 속성(width?)이라, 빌드의 타입 검사는 이 빠뜨림을 잡지 않습니다. 배포 판은 이 검사를 하지 않아, width 없는 <img>를 그립니다(③).

다 봤으면 지운 width={100} 줄을 되살려 저장합니다.

자주 틀리는 곳

틀린 생각: next/image는 모든 그림을 /_next/image로 줄여 보낸다.

맞는 규칙: SVG 그림은 줄이지 않고 src를 그대로 둡니다. 줄여 보내는 것은 PNG · JPG 같은 그림입니다(Next.js 문서 Image).

틀린 생각: 문서의 예처럼 <html>에 글꼴 클래스를 걸면 앱 전체 글자가 바뀐다.

맞는 규칙: globals.css의 body에 font-family가 있으면 그 규칙이 이깁니다. 이 앱은 <body>에 겁니다(2절).

틀린 생각: 글꼴 파일은 쪽을 열 때마다 Google Fonts에서 받는다.

맞는 규칙: next/font가 받아 둔 파일을 내 앱의 주소 /_next/static/media/…⁠에서 보냅니다.

확인 문제

문제 1. <Image>에서 width를 빠뜨리고 개발 판에서 그 쪽을 열면 어떻게 될까요?

  • ① 오류가 나 쪽을 그리지 못하고, 터미널에 width가 없다는 오류가 찍힌다
  • ② 그림 파일의 크기로 그린다
  • ③ 빌드할 때만 오류가 난다
정답

①입니다. <Image>는 개발 판에서 width가 없으면 오류를 던집니다(예제).

  • ② 그림 파일의 크기를 읽어 채우지 않습니다.
  • ③ 이 오류는 개발 판에서 쪽을 그릴 때 납니다. 빌드의 타입 검사는 width를 꼭 받지 않습니다.

문제 2. next/font/google로 건 글꼴 파일을 브라우저는 어디서 받을까요?

  • ① Google Fonts의 서버
  • ② 쓰는 사람 컴퓨터에 깔린 글꼴
  • ③ 내 앱의 주소 /_next/static/media/…
정답

③입니다. next/font가 글꼴 파일을 받아 내 앱의 파일로 둡니다(2절).

  • ① 브라우저는 Google에 요청하지 않습니다.
  • ② 깔린 글꼴을 쓰지 않고 받은 파일을 씁니다.

문제 3. <html>의 className에 noto.className을 걸었는데 글자가 바뀌지 않았습니다. 까닭은 무엇일까요?

  • ① subsets에 korean이 없어서
  • ② globals.css의 body에 있는 font-family가 이겨서
  • ③ 개발 판에서는 글꼴을 받지 않아서
정답

②입니다. <html>에서 물려받은 값보다 body에 바로 건 규칙이 이깁니다(2절).

  • ① subsets는 미리 받을 묶음일 뿐입니다. 한글 조각은 따로 받습니다.
  • ③ 개발 판도 글꼴을 받아 내 주소에서 보냅니다.
이 레슨에서 바꾼 파일

app/layout.tsx — 바닥글 그림 · 글꼴

app/layout.tsx
import type {
  Metadata,
} from 'next';
import Image from 'next/image';
import {
  Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
  '@/components/TabBar';

const noto = Noto_Sans_KR({
  subsets: ['latin'],
});

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body
        className={
          noto.className
        }
      >
        <TabBar />
        {children}
        <footer>
          바닥글
          <Image
            src="/next.svg"
            alt="Next.js"
            width={100}
            height={20}
          />
        </footer>
      </body>
    </html>
  );
}

export default RootLayout;

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

Next.js 목차로