
모듈이란 애플리케이션을 구성하는 개별적 요소로서 재사용이 가능한 코드 조각을 말한다.
ES6의 모듈기능을 사용하지 않으면 각각의 js파일들은 자신들의 스코프를 가지지 않는다. 즉 모든 js파일들은 하나의 전역을 공유하게 된다.
이를 해결하기 위해 script파일에 type="module" 속성을 추가해주면 js파일마다 각자의 스코프를 가지게 된다.
모듈 안에서 선언한 식별자를 외부 모듈이 참조할 수 있게하는 키워드
export let x= 'hello';
export function square(x){
return x*x;
}
console.log(x);
모듈에서 export 한 대상을 로드하기 위해 사용하는 키워드
import { x, square} from './practice.js';
console.log(x); // hello
console.log(square(4)); // 16
모듈이 export한 식별자를 각각 지정할 필요 없이 하나의 이름으로 한번에 import할 수 있다.
import * as pr1 from '/practice.js';
console.log(pr1.x);
console.log(pr1.square(4));
이름을 변경하여 import 할 수 있다.
import {x as xx , square as square2} from './practice.js';
console.log(xx);
console.log(square2(4));
모듈에서 식별자 하나만 export 하고 싶을 경우 export 뒤에 default 키워드 사용
//practice1.js
export default x= 'hello';
//practice2.js
import x from './practice.js';
console.log(x); // hello