본문 바로가기
C++ 200제/코딩 IT 정보

TypeScript JSON 모듈 import 사용 방법

by vicddory 2019. 12. 2.

TypeScript 2.9에는 새로운 기능이 도입되었습니다. --resolveJsonModuleTypeScript 컴파일러 옵션으로 JSON 모듈을 가져올 수 있게 되었습니다.


#require 호출로 JSON 모듈 가져오기

TypeScript로 작성된 Node 애플리케이션이 있다고 가정하고 다음 JSON 파일을 가져온다고 가정합니다.


{
"server": {
"nodePort": 8080
}
}


Node에선 다음처럼 사용할 수 있습니다.

require를 CommonJS 모듈 사용할 때와 같은 방법으로 JSON 파일을 import 합니다.


const config = require("./config.json");


JSON은 자동으로 일반 JavaScript 객체로 역직렬화됩니다. 이를 통해 구성 객체의 속성에 쉽게 액세스할 수 있습니다.


"use strict";


const express = require("express");
const config = require("./config.json");


const app = express();


app.listen(config.server.nodePort, () => {
console.log(`Listening on port ${config.server.nodePort} ...`);
});


여기까진 그런대로 잘 됩니다.



정적 import 선언을 통해 JSON 파일 가져오기

이제 CommonJS 모듈 대신 기본 ECMAScript 모듈을 사용한다고 가정합니다. 즉, require 호출을 정적 import 선언으로 변환합니다.


// We no longer need the "use strict" directive since
// all ECMAScript modules implicitly use strict mode.

import * as express from "express";
import * as config from "./config.json";

const app = express();

app.listen(config.server.nodePort, () => {
console.log(`Listening on port ${config.server.nodePort} ...`);
});


이렇게 하면, 2번 라인에서 타입 오류가 발생합니다. TypeScript를 사용하면 JSON 모듈을 바로 가져올 수 없습니다. 이것은 TypeScript 팀이 의도한 디자인 결과 때문입니다. 큰 JSON 파일을 가져오면 많은 메모리가 소비되므로 --resolveJsonModule 컴파일러 플래그를 활성화한 뒤 해당 기능을 선택해야 합니다.


사람들이 의도적으로 선택하도록 유도하는 것 = 그것은 사용자가 비용 발생을 이해한다는 것을 의미합니다.


tsconfig.json 파일에 resolveJsonModule 옵션을 활성화하세요.


{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"strict": true,
"moduleResolution": "node",
"resolveJsonModule": true
}
}


--resolveJsonModule 활성화하면 TypeScript 파일에 타입 에러가 발생하지 않습니다. 더 좋은 것은 타입 체크와 자동 완성 기능이 제공된다는 것입니다!

영상 내용 : app.listen(config.server.nodePort 자동 완성




위에 표시된 컴파일러 옵션으로 TypeScript 파일을 컴파일하면 다음과 같은 JavaScript 출력을 확인할 수 있습니다.


"use strict";

Object.defineProperty(exports, "__esModule", { value: true });

const express = require("express");
const config = require("./config.json");
const app = express();

app.listen(config.server.nodePort, () => {
console.log(`Listening on port ${config.server.nodePort} ...`);
});


출력 내용은 초기 require 버전과 거의 똑같습니다.


"use strict";

const express = require("express");
const config = require("./config.json");
const app = express();

app.listen(config.server.nodePort, () => {
console.log(`Listening on port ${config.server.nodePort} ...`);
});


사용하기 쉽네요. 하나의 컴파일러 옵션 하나만으로 TypeScript Json 모듈을 쉽게 사용할 수 있습니다.


관련 글

[C# JSON] JSON 생성 및 사용, 예제 소스

TypeScript 강좌 4. 호환성 tsconfig.json

TypeScript 문자열 숫자 변경 - 단항연산자 (string to int)

댓글