Notice
Recent Posts
Recent Comments
Link
솔미는 성장중
[JS] 모듈 본문
728x90
🎯 모듈이란?
특정 데이터들의 집합(파일)
- 모듈 개념을 사용하기 위해선 index.html 파일에서 main.js를 연결해주는 script태그에 type="module" 속성이 추가되어있어야 한다!
- 예시)
//module.js
export const hello = 'Hello world!'
//main.js
import {hello} from './module.js'
console.log(hello) // Hello world!
🎯 Export & Import 패턴
1. 기본 내보내기
: module.js에서 이름이 없으므로 import할 때 임의로 이름 지정 가능!
: 하나의 모듈에서 기본 내보내기를 통해서 내보낼 수 있는 데이터는 딱 하나!!
//module.js
export default 123
//main.js
import number from './module.js'
console.log(number) // 123
2. 이름 내보내기
: 여러 개의 데이터를 내보낼 수 있다.
//module.js
export default 123
export const str = 'ABC' //추가된 부분
export const arr = [] //추가된 부분
export function hello(){} //추가된 부분
//main.js
import number, {str, arr, hello} from './module.js'
console.log(number) // 123
console.log(str) //ABC
console.log(arr) //[]
console.log(hello) //hello(){}
🎃 이름 내보내기 방식을 사용할 때 이름을 바꿔 불러오고 싶으면 !?!?!?
//main.js
import {str as abc, arr, hello as h} from './module.js'
console.log(abc) //ABC
console.log(arr) //[]
console.log(h) //hello(){}
🎃 module.js 내에 있는 모든 데이터를 하나의 변수에 할당해 사용하고 싶다면 !?!?!?
//main.js
import * as xyz from './module.js'
console.log(xyz)
/* arr: Array(0)
default: 123
hello: f hello()
str: "ABC" */
동기 : 순차적으로 코드 실행 O
비동기 : 순차적으로 코드 실행 X
fetch메소드를 사용할 때 비동기 코드는 서버로 갔다오는 시간을 모르기 때문에 동작하는 순서를 보장할 수 없음.
🎯 동적으로 모듈 가져오기
기본적으로 import는 최상단에 적어야 한다.
그럼 코드 중간에서 모듈을 가져오고 싶으면 어떻게 해야하나요?
or
함수 내에서 모듈을 불러오려면 어떻게 해야하나요?
import() 함수 이용하기!!
//main.js
//import * as xyz from './module.js'
//console.log(xyz)
setTimeout(() => {
import('./module.js').then(xyz => {
console.log(xyz)})
},1000)
import(경로)가 완료되면 이후 과정 실행
🎃 비동기 패턴을 배우고 수정해본다면?
setTimeout(async() => {
const abc = await import('./module.js') //module.js를 가져올때 얼마나 시간 걸릴지 모르니 await를 통해 기다려줌
console.log(abc)})
},1000)
//1초 후에 결과 출력
🎯 가져온 모듈 바로 내보내기
utils.js에서 export 할 모듈을 모두 작성하기!
//a.js
export const a = () => 123
//b.js
export const b = () => 456
// utils.js
export { a } from './a.js'
export { b } from './b.js'
//main.js
import { a, b } from './utils.js'
console.log(a()) //123
console.log(b()) //456
cf) JSON 데이터 import 하는 경우
import하면 자동으로 문자 데이터였던 JSON 데이터를 변환해준다.
728x90
'JavaScript' 카테고리의 다른 글
[JS] 불변성 (0) | 2023.07.31 |
---|---|
[JS] DOM (0) | 2023.07.31 |
[JS] fetch() (0) | 2023.07.31 |
[JS] 동기/비동기 (콜백 패턴, promise, Async & Await, Resolve, Reject, 에러 핸들링, 반복문에서의 비동기) (0) | 2023.07.31 |
[JS] prototype + 배열 만드는 방법 (1) | 2023.07.19 |