Nextjs+Typescript 에서 import image하기

Nextjs+Typescript 에서 import image하기

Module parse failed: Unexpected character ' ' (1:0)

날 하루종일 괴롭힌 에러 next-images도 하고 Next/image도 써보고 next.config.js에 모듈도 추가해주고 node도 업데이틀하고 스택오버플로우와 구글링으로 모든걸 다 해봤지만 에러는 여전했다. 잠시 휴식 후 천천히 찾아보니 Typescript를 사용한다면 추가적인 설정들이 필요하다.

next-images 설치

package.json에 next-images가 없다면 next-images를 설치해준다 npm install --save next-images

next-env.d.ts

next-env.d.ts 파일에 아래의 코드를 추가해준다. 없다면 root 경로에 생성한다.

/// <reference types="next-images" />

/// 도 포함

next.config.js

next.config.js 파일에 아래의 코드를 추가해준다. 없다면 root 경로에 생성한다.

const withImages = require('next-images'); module.exports = withImages();

tsconfig.json

tsconfig.json 에서 compilerOptions 부분에 typeRoots를 설정해준다.

{ "compilerOptions": { "target": "es5", // 생략 "typeRoots": ["./node_modules/@types", "./@types"] },

custom.d.ts

custom.d.ts 파일에 아래의 코드를 추가해준다. 없다면 root 경로에 생성한다. 파일이름은 꼭 custom.d.ts 이 아니여도 된다. ex) index**.d.ts** 등

declare module '*.png' { const src: string; export default src; }

Import image

이제 리액트에서 처럼 Import image가 가능하다. import logo from '../../Icon/Icon.png';

function Header() { return ( <img src={Icon} alt="logo" /> ) } export default Header;

추가

여전히 next/image를 이용한 Image 태그(컴포넌트)는 타입에러가 생겨 기존처럼 img 태그를 사용한다. svg 파일도 사용하기 위해 모듈을 추가해줬다.

JP
이중표Frontend Engineer

3년차 프론트엔드 개발자. Next.js, React, TypeScript 기반 웹 애플리케이션 개발 전문. 대규모 트래픽 환경에서 SSR·ISR 렌더링 전략 설계 경험.

이력서 보기