[JS] 모듈

Local Gaji·2023년 5월 14일

JavaScript

목록 보기
6/18

1. 모듈 : 개요

내보내기 & 가져오기

// module.js  : 모듈 파일에서 내보내기
export const data = "Hello"

// main.js    : 모듈 파일을 가져오기
import { data } from "./module.js"  

2. 가져오기와 내보내기 패턴

기본 내보내기

  • 이름 없이 내보내기, 메인에서 데이터 이름 지정
  • 1개의 데이터만 내보낼 수 있음
export default 123                  // module 

import number from "./module.js"    // main

이름 내보내기

필요한 데이터만 import

export const str = "abc"           
export function func() {}       

import { str } from "path"  
import { str, func } from "path"  
import * from "path"    
import * as x from "path"         
// 모든 데이터를 x라는 이름으로 가져오기

import number, { str } from "path"
// 기본 내보내기, 이름 내보내기 데이터 같이 가져오기

import { str as s } from "path"
// 가져오기 하면서 데이터 이름을 새로 정의하기

동적으로 모듈 가져오기

코드 중간에서 모듈 가져오기


import('path').메소드()


setTimeout(() => {
  import('path').then(x => {
    console.log(x)
  })
}, 1000)

utils.js

// utils.js : 모듈을 가져와서 한번에 내보내기
export { a } from './a.js'
export { b } from './b.js'

// main.js : utils.js 가 가져온 모듈들을 가져오기
import { a, b } from './utils.js'

0개의 댓글