728x90
반응형
모듈
- 특정 데이터들의 집합(파일)
- 모듈 IMPORT, EXPORT
- 파일로 정리하는 것 = 모듈화
1) 기본 내보내기 / 이름 내보내기
main.js
// 기본 내보내기는 import 할 때 이름 변경 가능
// 이름 내보내기를 가져올 땐 {} 사용
import number, {str as xyz, arr, hello as h} from './module.js'
import * as abc from './module.js'
console.log(xyz)
console.log(arr)
console.log(h)
console.log(abc)
module.js
// 기본 내보내기(default 사용)
// 한 모듈에서는 한 데이터만 내보내기 가능
export default 123;
// 이름 내보내기
// 여러개 내보내기 가능
export const str = 'ABC';
export const arr = [];
export const hello = ()=>{};
2) then() 메소드, async/awat 사용
import * as abc from './module.js'
setTimeout(() => {
// import 키워드로 경로를 작성하는 내용을 import 함수의 인수로 사용 가능
// 이 모듈을 가지고 오면 그때 실행할 메소드 then 작성
// then 메소드의 매개변수가 모듈에서 가지고 온 모든 데이터
import('./module.js').then((abc)=>{
console.log(abc)
})
}, 1000);
import * as abc from './module.js'
setTimeout(async () => {
// import는 비동기로 동작
// 위 settimeout과 같은 결과
const abc = await import('./module.js');
console.log(abc);
}, 1000);
3) 여러 개 파일 한번에 import
main.js
// a와 b 함수를 모두 포함한 util.js 파일 import
import {a, b} from './util.js'
console.log(a())
console.log(b())
a.js
export const a = () => 123
b.js
export const b = () => 456
util.js
export {a} from './a.js'
export {b} from './b.js'
728x90
반응형
'JS, TS' 카테고리의 다른 글
[JS] DOM (1) | 2024.01.14 |
---|---|
[JS] 동기/비동기 (1) | 2024.01.14 |
[JS] 표준내장객체 3 (정적 메소드, 객체, JSON) (0) | 2024.01.12 |
[JS] 표준내장객체 2 (배열) (0) | 2024.01.12 |
[JS] 표준내장객체 1 (문자, 숫자, 수학, 날짜) (0) | 2024.01.12 |