모듈
간단하게 말하면 자바스크립트 파일 하나.
복잡한 코드를 기능에 따라 파일로 나눠서 관리하면 코드를 효율적으로 관리할 수 있고, 비숫한 기능이 필요할 때 재사용 할 수도 있다.
모듈 스코프
모듈은 모듈만의 독립적인 스코프를 가지고 있어야 한다.
HTML 파일 안에서 자바스크립트 파일을 불러올 때 모듈 스코프를 갖게 하려면 script 태크에 type 속성을 module로 지정한다.
1
2
3
<body>
<script type="module" src="index.js"></script>
</body>
모듈 문법
- export: 모듈 스코프를 가진 파일에서 외부로 내보내고자 하는 변수나 함수를 export 키워드를 통해 내보낸다.
- import: 모듈 파일에서 내보낸 변수난 함수들은 다른 파일에서 import 키워드를 통해 가져온다.
1
2
3
4
5
6
// printer.js
export const title = "CodeitPrinter";
export function print(value) {
console.log(value);
}
1
2
3
4
// index.js
import { title, print } from "./printer.js";
print(title);
이름 바꿔 import 하기
import 키워드를 통해 모듈을 불러올 때 as 키워드를 활용하면 import 하는 대상들의 이름을 변결할 수 있다.
이렇게 하면 import 하는 여러 파일에서 불러오는 대상들의 이름이 중복되는 문제를 해결 가능하다.
1
2
3
4
5
import { title as printerTitle, print, printArr } from "./printer.js";
import { title, data as members } from "./members.js";
printer(title);
arrPrinter(members);
한꺼번에 import 하기
import할 때 * (와일드카드 문자)를 사용하면 모듈 파일에서 export 하는 모든 대상을 하나의 객체로 불러올 수 있다.
1
2
3
4
import * as printerJS from "./printer.js";
console.log(printerJS.title); // CodeitPrinter
console.log(printerJS.print); // ƒ print(value) { console.log(value); }
한꺼번에 export 하기
선언된 변수나 함수를 하나의 객체로 모아 한꺼번에 내보밸 수 있다. 이때 as 키워드를 활용하면 이름을 변경해서 export 할 수도 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
const title = "CodeitPrinter";
function print(value) {
console.log(value);
}
function printArr(arr) {
arr.forEach((el, i) => {
console.log(`${i + 1}. ${el}`);
});
}
export { title as printerTitle, print, printArr };
default export
default 키워드를 사용해서 export를 하면 모듈 파일에서 기본적으로 export할 대상을 정할 수 있다.
export 할 대상이 하나라면 default 키워드를 사용하는것이 효율적!!
1
2
3
4
5
6
7
const title = "CodeitPrinter";
function print(value) {
console.log(value);
}
export default print;
default 키워드를 사용하면 import 할 때 기본적으로 다음과 같이 불러온다.
1
2
3
4
import { default as printerJS } from "./printer.js";
console.log(printerJS.title); // CodeitPrinter
console.log(printerJS.print); // ƒ print(value) { console.log(value); }
축약형 문법으로도 import 할 수 있다.
1
2
3
4
import printerJS from "./printer.js";
console.log(printerJS.title); // CodeitPrinter
console.log(printerJS.print); // ƒ print(value) { console.log(value); }