Next.js

[Next.js] Next.js Local 폰트 적용, 동적라우팅, Image 세팅

ejunyang 2024. 7. 3. 11:38

 

🔗 Local font 사용 공식문서 참조

 

Optimizing: Fonts | Next.js

Optimize your application's web fonts with the built-in `next/font` loaders.

nextjs.org

✨ next/font 를 사용하면 폰트를 최적으로 로드할 수 있다. 모든 글꼴 파일에 대한 자동 자체 호스팅이 내장되어 있어, 레이아웃 이동 없이 최적으로 글꼴을 로드 할 수 있다.

 

 

 

Next.js Local 폰트 적용

next/font/google

  • layout의 기본세팅은 inter font로 되어있다.
  • 구글 폰트의 CDN 서비스를 통해 폰트를 불러올 수 있다.
  • 서버사이드 렌더링(SSR)과 클라이언트사이드 렌더링(CSR)을 지원한다.

next/font/local

  • 웹 폰트 다운로드 시간을 절약하고, 오프라인 사용 가능성을 제공한다.
  • 이미지와 마찬가지로 클라이언트 측에서 파일을 다운로드할 필요가 없으므로 페이지 로드 속도를 향상시킬 수 있다.

 

 

 

📁 app / 📁 fonts 폴더 생성

위 경로대로 폴더를 생성하고 다운받은 font 파일을 넣어준다. localFont import 후에 body 태그 안에 {myFont.className} 이라고 써주면 body 태그 내에서 모든 폰트가 적용된다.

import type { Metadata } from "next";
import "./globals.css";
import QueryProvider from "./provider";
import localFont from "next/font/local";

export const metadata: Metadata = {
  title: "Pokémon",
  description: "포켓몬 도감 웹페이지 입니다.",
};

const myFont = localFont({
  src: "./fonts/DungGeunMo.ttf",
  weight: "400",
  style: "normal",
  display: "swap",
});

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="ko">
      <body className={myFont.className}>
        <div className="flex flex-col justify-center items-center">
          <h1 className="text-center w-[300px] mx-auto my-10">
            <img src="/pokemon.png" alt="포켓몬 로고" className="w-[100%]" />
          </h1>
          <QueryProvider>{children}</QueryProvider>
        </div>
      </body>
    </html>
  );
}

 

 

 

id 값으로 동적라우팅

params를 props로 받아 구조분해 할당 후 사용할 수 있다. props는 types 폴더에 인터페이스로 따로 정의해 주었다.

const DetailPokemonPage = async ({ params }: Props) => {
  const { id } = params;
  const fetchPokemonData = async () => {
    try {
      const response = await axios.get(
        `http://localhost:3000/api/pokemons/${id}`
      );
      return response.data;
    } catch (error) {
      console.error("데이터를 가져오지 못했습니다.", error);
      return [];
    }
  };

 

사용방법 1)

export interface Props {
  params: {
    id: number;
  };
}

 

사용방법 2)

const DetailPokemonPage = async ({ params }: { params: { id: number; };) => {
  const { id } = params;
  };

 

 

 

 

Image 세팅

next에서 기본으로 제공해주는 Image 기능을 사용해보려고 한다. 그러기 위해선 필수로 next.config.mjs를 설정해주어야한다.

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "raw.githubusercontent.com",
      },
    ],
  },
};

export default nextConfig;

 

width, height, alt 속성을 꼭 채워주어야한다. 안그럼 오류가 나더라.. Next.js에서 제공하는 Image 태그를 사용하는 이유는 큰 이미지를 작은 이미지로 줄여주고, 웹사이트 용량이 줄어들기 때문이다. 

<Image
   src={pokemonData.sprites.front_default}
   width={150}
   height={150}
   alt="포켓몬 이미지"
/>

 

이미지 크기를 고정하고싶지 않을 때는 fill 속성을 사용하면 된다. 대신 부모태그에 position: relative 를 써주어야한다.