JavaScript 모듈 정의 방법

  • ES6 모듈과 동일하게 최상위 부분의 import, 또는 export가 있는 것을 모듈로 간주함
  • 반대로 import, export 식이 없으면 파일 내 내용은 전역 범위에서 실행됨
    import, export가 없지만 모듈로 처리하고 싶으면 빈 export 객체 생성 필요
export {};
  • 모듈은 따로 export하지 않는 이상 자체 범위 내에서 실행됨

TypeScript에서의 모듈

Syntax

  • export default <-> import
// hello.js
export default function helloWorld() {
  console.log("Hello, world!");
}

// 다른 파일
import helloWorld from "./hello.js";
helloWorld();
  • export <-> import
// maths.js
export var pi = 3.14;
export let squareTwo = 1.41;
export const phi = 1.61;
 
export class RandomNumberGenerator {}
 
export function absolute(num: number) {
  if (num < 0) return num * -1;
  return num;
}

// 다른 파일
import { pi, phi, absolute } from "./maths.js";
 
console.log(pi);
const absPhi = absolute(phi);
  • 위의 두 구문은 혼합해서 사용 가능
// maths.js
export const pi = 3.14;
export default class RandomNumberGenerator {}
 
import RandomNumberGenerator, { pi as π } from "./maths.js";
 
RandomNumberGenerator;
console.log(π);
  • 변수의 이름을 다르게 사용하고 싶으면 import {old as new} 식으로 가져오기
import { pi as π } from "./maths.js";
 
console.log(π);
  • export된 모든 변수들을 가져오고자 하면 * as name으로 가져옴
import * as math from "./maths.js";
 
console.log(math.pi);
const positivePhi = math.absolute(math.phi);
  • 변수를 가져오지는 않고, 파일과의 상호작용만 필요하면 import "file" 식으로 가져오기
import "./maths.js";
 
console.log("3.14");
  • 타입스크립트에서는 ES6 모듈에 타입, 인터페이스도 같이 내보낼 수 있음
// animal.ts
export type Cat = { breed: string; yearOfBirth: number };
 
export interface Dog {
  breeds: string[];
  yearOfBirth: number;
}
 
import { Cat, Dog } from "./animal.ts";
type Animals = Cat | Dog;
  • 타입스크립트에는 타입만을 주고받을 수 있는 import type, export type이 있음
// animal.ts
export type Cat = { breed: string; yearOfBirth: number };
export type Dog = { breeds: string[]; yearOfBirth: number };
export const createCatName = () => "fluffy";
 
// 가능
import type { Cat, Dog } from "./animal.ts";
export type Animals = Cat | Dog;
 
// 'createCatName' cannot be used as a value because it was imported using 'import type'.
import type { createCatName } from "./animal.ts";
const name = createCatName();
  • CommonJS 모듈을 사용해서도 모듈을 가져올 수 있음
/// maths.js
function absolute(num: number) {
  if (num < 0) return num * -1;
  return num;
}
 
module.exports = {
  pi: 3.14,
  squareTwo: 1.41,
  phi: 1.61,
  absolute,
};

// 다른 파일
const maths = require("maths");
maths.pi;

// 구조분해 문법도 사용 가능
const { squareTwo } = require("maths");
squareTwo;

Module Resolution

  • import, require 문의 원래 파일을 찾는 알고리즘을 정하는 컴파일러 옵션을 정할 수 있음
  • 타입스크립트에서는 Classic, Node 2가지 방식이 있으며, Node 옵션을 사용하면 Node.js에서 import 하는 방법을 고려해 .ts, d.ts의 추가적인 체크를 하게 됨
    참고

Module Output Options

  • target: 어느 버전의 자바스크립트로 컴파일 할 것인가?
  • module: 어떤 모듈 시스템을 사용할 것인가 결정
profile
냐아아아아아아아아앙

0개의 댓글

Powered by GraphCDN, the GraphQL CDN