728x90
728x90

모듈 방식 사용하기

들어가며

  • 타입스크립트(TypeScript)에서 모듈 방식을 사용하는 방법을 정리해본다.

 

방법

  • 타입스크립트 파일(.ts/.tsx)은 기본적으로 모듈(Module)로 간주되지 않고, 전역 범위스크립트로 처리된다.
    • 여러 파일에서 동일한 변수명을 생성할 경우, 오류가 발생한다.
fileA.ts
let name = 'stickman';
const susan = 'susan';

 

fileB.ts
const susan = 'susan'; // 오류 발생

 

  • 이때, 다음과 같이 2가지 방법으로 타입스크립트 파일을 모듈로 변환할 수 있다.

 

방법 ① : import, export 문 사용하기

  • 타입스크립트 파일에 import 또는 export 문을 추가하여 ES6 모듈로 취급되게 하는 방법이다.

 

actions.ts
export function sayHello(name: string): void {
console.log(`Hello ${name}!`);
}
export let person = 'susan';
export type Student = {
name: string;
age: number;
};
const newStudent: Student = {
name: 'peter',
age: 24,
};
export default newStudent;

 

test.ts
  • import 문을 이용하여 actions.ts 파일에서 export한 변수와 함수를 가져온다.
  • 이때 type의 경우, import 할 때 불러올 대상 이름 앞type 키워드를 붙일 수 있다.
import newStudent, { sayHello, person, type Student } from './actions';
sayHello('TypeScript');
console.log(person); // 'susan'
console.log(newStudent); // { name: 'peter', age: 24 }
const anotherStudent: Student = {
name: 'bob',
age: 23,
};
console.log(anotherStudent); // { name: 'bob', age: 23 }

 

방법 ② : 타입스크립트 설정 파일(tsconfig.json)에서 속성 추가하기

  • 타입스크립트에서 기본적으로 타입스크립트 파일이 모듈로 간주되도록 하기 위해서 타입스크립트 설정 파일(tsconfig.json)에서 몇 가지 속성을 추가해줄 수 있다.
    • 타입스크립트 설정 파일(tsconfig.json)은 프로젝트의 최상위 경로(/)에 위치한다.

타입스크립트 설정 파일의 모습

 

./tsconfig.json
  • moduleDetection 속성force로 하는 속성을 추가해준다.
    • importexport 문이 타입스크립트 파일에 없어도 모듈처럼 처리되게 할 수 있다.
  • module 속성ESNext로 하는 속성을 추가해준다.
    • ES6 모듈 구문이 사용된다.
    • CommonJS로 값을 지정해줄 경우, CommonJS 구문이 사용된다.
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext", // ✅ module
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"moduleDetection": "force", // ✅ module
/* Linting */
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

 

⇒ ✅ 표시한 부분을 추가해준다.

 

참고 : 자바스크립트 파일(.js) 사용하기

  • 타입스크립트는 자바스크립트 파일(.js)의 코드를 기본적으로 타입스크립트 코드로 인식하지 않는다.
    • 자바스크립트 파일(.js)에서 export 문을 사용할 경우 오류가 발생한다.
  • 이 문제를 해결하려면 타입스크립트 설정 파일(tsconfig.json)에 아래의 속성("allowJS": true)을 추가해준다.
./tsconfig.json
{
"compilerOptions": {
// ...
"allowJs": true // JS 파일 처리하기
// ...
},
"include": ["src"]
}

 

참고 사이트

 

Documentation - Modules

How modules work in TypeScript

www.typescriptlang.org

 

TSConfig Reference - Docs on every TSConfig option

From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

www.typescriptlang.org

 

TSConfig Option: moduleDetection

How this setting affects your build.

www.typescriptlang.org

 

TSConfig Reference - Docs on every TSConfig option

From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

www.typescriptlang.org

 

728x90
728x90

모듈 방식 사용하기들어가며방법방법 ① : import, export 문 사용하기방법 ② : 타입스크립트 설정 파일(tsconfig.json)에서 속성 추가하기참고 : 자바스크립트 파일(.js) 사용하기참고 사이트