-
typescript json import 방법 | 오류, 에러, 버그프로그래밍/버그(bug) 2022. 8. 10. 20:22
소스 코드
import * as serviceAccount from "./serviceAccount.json";
오류 메시지
"Cannot find module './serviceAccount.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.ts(2732)"
해결 방법
tsconfig.json에 추가 설정을 해줘야한다.
{ "compilerOptions": { // ... other options "resolveJsonModule": true, "esModuleInterop": true, // "moduleResolution": "node" } }
추가 설명
"resolveJsonModule": true
오류 메시지에서도 있듯이 typescript에서 json 파일을 import 하려면 기본적으로 활성화 해줘야 하는 옵션. 보통 이거 하나면 해결된다.
"esModuleInterop": true
CommonJS 모듈들을 ES6 모듈들 처럼 사용하게 해줌.
(예시로 import 할때 이전 버전과 호환성 문제로 import * as express from 'express' 같은 형식을 import express, { Router } from 'express' 처럼 사용할 수 있게 해준다. 하지만 import * as 로만 사용가능한 경우도 있으니 주의!)
"moduleResolution": "node"
위 두가지 옵션으로도 해결이 안된다면 마지막 옵션을 추가해 볼 수 있다. (이것도 import 관련해서 경로 및 호환성 문제. 아직 관련 문제가 안생겨 잘 모르겠다.)
참고 자료
How to Import a JSON file in TypeScript | bobbyhadz
To import a JSON file in TypeScript, set `resolveJsonModule` to `true` in your `tsconfig.json` file. Set `esModuleInterop` to `true` in `tsconfig.json`. Import the JSON file as `import employee from './employee.json'`.
bobbyhadz.com
질문이나 오류 발견 환영입니다.
'프로그래밍 > 버그(bug)' 카테고리의 다른 글
firebase signInWithCustomToken auth/custom-token-mismatch | 오류, 에러, 버그 (0) 2022.08.11 cloud functions express cors error with typescript | 오류, 에러, 버그 (0) 2022.08.11