타입스크립트 prettier 자동 포매팅 안될 때 해결 방안(require() of ES Module)

타입스크립트를 적용해보니 Prettier 자동 포매팅을 포함, 모든 설정이 제대로 먹히지 않는 경우가 생겼습니다.

그래서 아래의 오류가 발생을 했고 해당 오류의 원인은 타입스크립트에서 require 가 사용되었기 때문입니다.

Error [ERR_REQUIRE_ESM]: require() of ES Module

format on save 설정 확인

가장 먼저 VS Code에서 format on save가 설정되어 있는지 확인을 합니다.

VS Code  >> 메뉴 >> 기본 설정 >> 설정  

format on save

prettier.config.cjs 파일의 수정

현재 require() of ES Module 오류가 난 파일에는 다음과 같이 설정이 되어 있습니다.

// prettier.config.js
module.exports = {
  plugins: [require("prettier-plugin-tailwindcss")],
};

즉, tailwind 플러그인을 인식하기 위해 require가 사용되어 있습니다.

하지만 타입스크립트에서는 기본 설정만으로는 require를 인식하지 못하므로 다음과 같이 타입스크립트 방식으로 바꾸어 주었습니다.

import type { Options } from 'prettier';
import prettierPluginTailwindcss from 'prettier-plugin-tailwindcss';

const prettierConfig: Options = {
  plugins: [prettierPluginTailwindcss],
};

export default prettierConfig;

ts 확장자로 변경

아직은 .cjs 확장자이므로 타입스크립트에서 인식하지 못하기 때문에 해당 파일을 .ts 확장자로 변경해 줍니다.

TS 확장자로 바꾼 후 import 구문으로 변경

이제 정상적으로 prettier 설정이 인식되는 것을 확인할 수 있고, 저장 시 format 설정도 잘 작동합니다.

그 밖에 도움이 되는 글

타입스크립트 ‘module’ is not defined (feat.eslint)

내 웹페이지 구글 폰트 삽입 방법(+복수의 폰트)