js에서 import를 하는 방법이 너무 많고 맨날 좀만 틀리면 지랄해대서 이걸 좀 알고 가야곘다.
#
# import
## CommonJS (require)
nodejs의 스탠다드로, Babel등의 transpiler가 필요없이 사용할 수 있다.
``` js
// 전체 모듈을 로드
const lodash = require("lodash")
// 특정 함수나 값만을 가져오는 구조분해
const {map} = require("lodash")
ESM은 js에서 모듈 작업을 위한 최신 표준이다. 최신 브라우저와 nodejs v12에서부터 지원된다.
import express from 'express'
import { Router } from 'express'
import * as mathFunctions from './math'
import express, { Router } from 'express'
require
and import
동기 vs 비동기
require
는 동기로, 모듈이 전부 로드 되기 전까지 나머지 코드가 실행되지 못한다.
import
는 비동기적으로, 조금 더 최적화된 로드가 허용된다.
static vs dynamic
import
는 static으로, 코드의 가장 위에 있어야 하지만, require는 동적인 import가 가능해
어디에서나 (함수 내부에서도 가능함) 존재할 수 있다.
interop
import
가 새로운 표준이 되어가고 있긴 하지만 아직 모든 lib나 환경이 이를 지원하지는 않는다.
지금은 둘 다 적절히 써야한다. 특히 디폴트 export를 사용할 때.
file extensions nodejs에서 ESM을 사용할 때 import path에 확장자까지 써줘야 한다.
module.exports = function myFunction() { ... }
export
객체에 붙여서 export할 때. exports.myFunc = function(){...}
exports.myVariable = 42;
export default function myFunc() {...}
export function myFunction() {...}
export const myVar = 42
function myFunction(){...}
const myVar = 32;
export { myFunction, myVar }
function myFunc(){...}
export { myFunc as anotherName }
Single vs. Multiple Exports commonJS는 하나의 값이나 여러 개의 값을 포함한 객체를 export 할 수 있게 해준다. ESM은 default와 named exports를 명시적으로 나눈다.
Immutable Exports ESM export는 불변성을 가진다. importing file에서 변경할 수 없다. commonJS의 exports는 변경될 수 있따.
Live Binding
ESM exports는 live binding
이다. 즉, exporting module에서 export된 값을 바꾸면
이는 모든 import하는 모듈에 반영된다. CommonJS는 이런 특성은 없다.
TS는 ECMAScript를 따르므로 모듈 import, export는 es6+와 동일하다. 다만, 정적 타입 검사를 추가적으로 하기 때문에 이 점이 영향을 미칠 수 있다.
ts에서는 type을 export, import할 수 있다.
import type { MyType } from "./my-types";
export type MyType = { ... }