[TIL] next.js 13 로컬 json 파일 가져오는 방법 (+ img 외부에서 불러오는 법)

대빵·2023년 12월 27일

next.js에서 로컬 json 파일 가져오는 방법

필요한 데이터를 .json 파일로 저장

/public폴더 경로에 저장
public 내부에서 폴더나 파일명은 원하는 이름으로 지정한다.

// 파일 경로: /public/data/data.json

[
	{
	 "id": 1,
	 "title": "abc",
	 "image": "http://example.com/1234.jpg",
     },
     {
	 "id": 2,
	 "title": "def",
	 "image": "http://example.com/5678.jpg",
     },
     {
	 "id": 3,
	 "title": "ghi",
	 "image": "http://example.com/9012.jpg",
     },
.....
]

require 함수를 사용하여 원하는 곳에 가져오기

require()
node.js에서 제공하는 함수.
Next.js에서 /public 디렉토리에 있는 정적 파일은 자동으로 서버와 클라이언트 모두에게 노출된다.
따라서 public에 있는 파일은 require 함수를 사용하여 가져올 수 있다.

next13버전에서는 getStaticProps같은 함수들은 지원하지 않는다, 혹시 Data Fetching이 궁금하면 [NXET.js 공식문서]를 참고하는게 좋을 거 같다(https://nextjs.org/blog/next-13#data-fetching)

비동기 통신을 하는 것이 아니므로 getData함수나 json파일을 변환해줄 필요없이 가져오기만 하면된다.

import React from 'react'

export default function page() {
  // JSON 파일 가져오기
  const datas = require('/public/data/data.json')

  return (
    <div>
      <h1>{datas.title}</h1>
      <section>
       {datas?.map((data) => (
          <div key={data.id}>
            <Link href={`/data/${data.id}`}>
              <Image
                src={data.image}
                alt={data.title}
                width={200}
                height={200}
              />
              <p>{data.title}</p>
            </Link>
          </div>
        ))}
    </div>
  )
}

이미지 외부에서 불러오기

NXET.js 공식문서

// next.config.js

const nextConfig = {
  images: {
    domains: ['assets.example.com'],
  },
};

next.config.js에서 images.domains를 추가, url은 에러 메시지로 뜬 주소를 넣는다.

0개의 댓글