home

    23-08-12

    TypeScript 타입 모듈이란 ?

    타입 모듈에 대해 알아보자.

    모듈이란 ?

    모듈은 프로그래밍 관점에서 특정 기능을 갖는 작은 단위의 코드를 의미한다. 모듈은 프로그램을 여러 개의 파일로 나누고, 각 파일 간에 코드를 공유하거나 재사용하는 방법을 제공한다


    자바스크립트모듈

    자바스크립트의 태생적 한계와 자바스크립트에 모듈화 개념을 도입하려는 여러 시도에 대해 알아보자.

    자바스크립트의 태생적 한계

    자바스크립트는 태생적으로 모듈이라는 개념이 없었다.파일 단위로 변수나 함수가 구분되지 않아 문제점이 많았다. 자바스크립트는 기본적으로 모두 전역 유효 범위를 갖는 특징이 있다. 그래서 이름이 서로 충돌하지 않게 유일한 변수나 함수 이름을 사용할 필요가 있다.

    자바스크립트 모듈화를 위한 시도들

    초창기에 자바스크립트는 모듈화를 지원하지 않았다. 이에 불편함을 느낀 사용자들이 여러 시도들을 했는데. 대표적인 두 가지가 바로 Common.js와 Require.js다.

    • Common.js를 사용한 방법
    // math.js
    module.exports = {
        add: function(a, b) {
            return a + b;
        }
    };
     
    // main.js
    const math = require('./math');
    console.log(math.add(2, 3)); // 5
    • Require.js 라이브러리를 사용한 방법
    <body>
      <script src="requires.js"></script>
      <script>
        require(["http://unpkg.com/vue@3/dist/vue.global.js"], function () {
          console.log('vue is loaded')
        })
      </script>
    </body>

    이 코드는 Require.js 라이브러를 내려받은 후 script 태그를 이용하여 로딩하고 require() 문법으로 외부 라이러를 가져온다. require()라는 문법을 이용하여 외부 라이브러리를 마치 모듈처럼 가져와서 사용할 수 있다.



    자바스크립트 모듈화 문법

    import와 export

    ES6부터 import와 export 문법을 지원했다.

    // math.js
    export function add(a, b) {
        return a + b;
    }
     
    // app.js
    import { add } from './math';
    console.log(add(2, 3)); // 5

    export default 문법

    export default는 한 모듈당 하나의 기본값만 내보낼 수 있다.

    // math.js
    export default function add(a, b) {
        return a + b;
    }
     
    // app.js
    import customAdd from './math';
     
    console.log(customAdd(2, 3)); // 5

    import as 문법

    import 문법을 사용할 때, as 키워드를 이용하여 가져온 모듈의 이름을 바꿀 수 있다.

    // math.js
    const customAdd = (a, b) => a + b;
    export default customAdd;
     
    // app.js
    import customAdd as myFunction from './math';
     
    console.log(myFunction(2, 3)); // 5

    import * 문법

    // math.js
    export function add(a, b) {
        return a + b;
    }
     
    export function subtract(a, b) {
        return a - b;
    }
     
    export {add, subtract}
     
    // app.js
    import * as mathFun from './math';
     
    console.log(mathFun.add(2, 3)); // 5
    console.log(mathFun.subtract(5, 2)); // 3

    export 위치

    export는 특정 파일에서 다른 파일이 가져다 쓸 기능을 내보낼 때 사용하는 키워드다, 변수나, 함수, 클래스에 모두 사용 가능하다.

    export const PI = 3.14159;
    export function add(a, b) {
        return a + b;
    }
     
    export class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
     
        greet() {
            console.log(`Hello, my name is ${this.name} `);
        }
    }


    타입스크립트 모듈

    타입스크립트에서도 똑같이 사용하면 된다.

    // math.ts
    export function add(a: number, b: number): number {
        return a + b;
    }
     
    // app.ts
    import { add } from './math';
     
    console.log(add(2, 3)); // 5

    타입스크립트 모듈을 다룰 때 추가로 알아야 할 점은 타입을 내보내고 가져올 수 있다는 것이다.

    // types.ts
    export interface Person {
        name: string;
        age: number;
    }
     
    // app.ts
    import { Person } from './types';
     
    const john: Person = {
        name: 'John',
        age: 30
    };
     
    console.log(john.name); // John


    타입스크립트 모듈화 문법

    타입 코드를 모듈로 내보내고 가져올 때 알아 두면 좋은 문법을 살펴보자

    import type 문법

    타입 코드일 때는 type이라는 키워드를 추가로 사용할 수 있다.

    // types.ts
    export Person = {
        name: string;
        age: number;
    };
     
    // app.ts
    import type { Person } from './types';
     
    const john: Person = {
        name: 'John',
        age: 30
    };
     
    console.log(john.name); // John

    import type을 사용하여 타입 코드인지 아닌지 명시할 수 있다.

    import inline type 문법

    import inline type 문법은 변수, 함수 등 실제 값으로 쓰는 코드와 타입 코드를 같이 가져올 때 사용할 수 있다. 여러 개를 가져올 때 어떤 코드가 타입인지 구분할 수 있는 장점이 있다.

    / hero.ts
    interface Hulk {
      name: string;
      skill: string;
    }
     
    function smashing() {
      return '';
    }
     
    export { Hulk, smashing };
     
    // app.ts
    import { type Hulk, smashing } from './hero';
     
    var banner: Hulk = {
      name: '배너',
      skill: '화내기'
    }

    한 파일에서 import로 여러 개의 값과 코드를 가져올 떄 import { type } 형태를 이용하여 가져온 코드가 타입인지 아닌지 명시할 수 있다.

    import와 import type 중 어떤 문법을 써야 할까?

    정답은 두두두두두두둥? 팀에서 정의된 코딩 컨벤션을 따르는 것이다. 혼자서 진행하는 프로젝트라면 스스로 규칙을 정하고 일관적으로 작성하면 된다.



    모듈화 전략:Barrel

    여러 개의 파일에서 모듈을 정의하여 가져올 때 배럴이라는 전략을 사용하면 좋다. 배럴이란 여러 개의 파일에서 가져온 모듈을 마치 하나의 통처럼 관리하는 방식이다.

    // mathUtils.ts
    interface add : {
      num : number;
    }
     
    export { add }
     
    // subtract.ts
    interface subtract : {
      num : number;
    }
     
    export { subtract }
     
    // index.ts 
    export { add } from './mathUtils';
    export { subtract } from './subtract';
     
    // app.ts
    import { add, subtract } from './math'

    여러 개의 모듈을 다룰 때는 마치 하나의 통에 가지런히 정리하듯이 배럴 모듈화 전략을 사용하여 코드 가독성을 높일 수 있다.

    출처

    캡틴 판교님의 쉽게 시작하는 타입스크립트
    https://www.yes24.com/Product/Goods/119410497