2021. 6. 23. 14:43ㆍ프론트엔드/Typescript
이번 챕터는 TypeScript라기보다는 JavaScirpt의 모듈 import / export에 대한 내용이다.
import와 export (ES Module Syntax)
한 파일에서 export하면, 다른 파일에서 그 파일을 지정하여 import할 수 있다.
export는 내보내기, import는 불러오기라고 생각하면 쉽다.
// export_file.ts
export default function helloWorld() {
console.log("Hello, world!");
}
// import_file.ts
import hello from "./hello.js";
hello();
위의 예제는 export_file 파일에서 export한 함수 helloWorld를, import_file 파일에서 import하여 호출하였다.
잘 보면 export한 함수는 helloWorld()지만, import할 때는 hello라고 import했다.
export default를 통해 export한 함수등은 import를 하는 곳에서 이름을 임의로 바꿀 수 있다.
그렇다면 여러가지를 export할때는 어떨까?
// maths.ts
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;
}
// other.ts
import { pi, phi, absolute } from "./maths.js";
console.log(pi);
const absPhi = absolute(phi);
일반 export는 갯수 제한없이 가능하지만, export default는 파일마다 단 1개만 가능하다.
export된 변수, 함수들은 Object형태로 import할 수 있다.
우리는 이전 포스팅에서 해체 대입(Destructuring assginment)에 대해서 알아봤다.
https://goldfishdiary.tistory.com/45
이 해체대입과 같이, 원하는 것만 뽑아서 사용하면 된다.
그러면 헷갈릴 수 있다. 그럼 일반 export랑 export default를 같이 쓰면 어떻게 될까?
// export_file.ts
export let age = 27;
export const name = "송인호";
let height = 178;
export default height;
// import_file.ts
import h, { age, name } from "./export_file";
다음과 같이 export default는 그 자체로, 일반 export는 해체 대입처럼 쓰면 된다.
하지만 이런 식으로는 불가능하다
// error!
// export default와 일반 export의 구분이 불가능 해서 못하게 한 듯
import h, etc from "./export_file";
console.log(etc.name, etc.age);
// 이렇게는 가능하다
// *는 all을 뜻한다. 모든 export된 변수를 가져오고 싶을 때 사용
import h, * as etc from "./export_file";
console.log(etc.name, etc.age);
import과정에서 에러가 난다. 그냥 규칙이니 이상하게 쓰려고 하지 말자.
import할 때 이름 바꾸기
export defualt로 내보내기 된건 이름을 마음대로 바꿔도 됐다.
그러면 일반 export는 어떻게 바꿀까?
// pi로 export된 걸, 이 파일에서는 π로 사용하겠다.
import { pi as π } from "./maths.js";
(파이 기호는 아스키코드가 아니기 때문에 PC 환경에 따라 문제가 생길 수 있으니 실제론 쓰지 말자)
(한글 변수도 쓸 수 있지만 안 쓰는 이유와 같음)
CommonJS 스타일의 모듈 (CommonJS Syntax)
CommonJS는 import / export전에 쓰이던 형태다.
이 형태를 보면 왜 import를 Object의 형태로 하는지 이해가 더 쉽다.
// export_file.ts
function absolute(num: number) { return num; }
module.exports = {
pi: 3.14,
squareTwo: 1.41,
phi: 1.61,
absolute,
};
// import_file.ts
const maths = require("maths");
maths.pi;
출처
'프론트엔드 > Typescript' 카테고리의 다른 글
실전 TypeScript 2 (0) | 2021.07.02 |
---|---|
근황 & 실전 TypeScript 1 (0) | 2021.07.01 |
TypeScript - Handbook(Classes) (0) | 2021.06.22 |
TypeScript - HandBook(Object Types) (0) | 2021.06.08 |
TypeScript - Handbook(More on Functions) (0) | 2021.06.01 |