본문 바로가기
Javascript

14. [JavaScript] Module

by 뽀롱트옌드 2023. 8. 27.

🏃🏻‍♀️ Module

[ 모듈, Module ]

  • 자바스크립트데이터들을 집합해놓은 문서(파일, .js)
    • 기능이나 데이터들을 파일로 구분하는것을 모듈화라고함
  • 모듈 가져오기 import, 모듈 내보내기 export 둘 중 하나의 키워드가 있어야 자바스크립트의 모듈에 해당됨
  • 자바스크립트모듈은 자바스크립트 파일을 호출하는 html의 script 태그에 type="module"속성이 있어야 활용가능함
/* index.html */
<script type="module" defer src="./main.js"></script>

- 내보내기, export

  1. default 기본 내보내기
    하나의 모듈(파일)에서 하나의 default와 하나의 데이터만 내보내기 가능함

export default 333


  1. 이름 내보내기
    변수에 데이터를 할당해 여러개를 내보낼수 있음
export const welcome = 'Welcome to the world of Poppy!';
export const numName = ['One', 'Two', 'Three'];
export function modulefn() {};

- 가져오기, import

import키워드는 javascript파일의 최상단에 위치해야함


  1. 기본 가져오기
import 기본내보내기(default)변수명지정, { welcome, numName, modulefn } from './module.js';

console.log(기본내보내기(default)변수명지정); // 333
console.log(welcome); // Welcome to the world of Poppy!
console.log(numName); // (3) ['One', 'Two', 'Three']
console.log(modulefn); // f modulefn() {}

  1. 가져오기에서 as키워드로 이름(변수명)을 변경할 수 있음
import { welcome as hello } from './module.js';

console.log(hello); // Welcome to the world of Poppy!

  1. 모듈(module.js)의 전체 데이터를 객체데이터로 가져오기
import * as moduleAll from './module.js';

console.log(moduleAll);
// {default: 333, __esModule: true}
// default: 333
// modulefn: ƒ modulefn()
// numName: Array(3)
// welcome: "Welcome to the world of Poppy!"
// __esModule: true
// get modulefn: ()=>modulefn
// get numName: ()=>numName
// get welcome: ()=>welcome
// [[Prototype]]: Object

  1. 원하는 시점(코드의 중간)에서 모듈 가져오기
  • import('src').then(Parameter=>{});
  • then메소드의 Parameter(매개변수 moduleAll)로 가져올 모듈의 모든데이터를 받음(*)
setTimeout(() => { 
    import('./module.js').then(moduleAll => {
        console.log(moduleAll);
    });
}, 1000);
  • async() => {const moduleAll = await import('src');}
  • 변수 moduleAll에 가져올 모듈의 모든데이터(*)를 담음
setTimeout(async () => { 
    const moduleAll = await import('./module.js');
    console.log(moduleAll);
}, 1000);

- 가져오자마자 내보내기, export

  • 여러개의 모듈을 다른 한개의 모듈에서 export키워드로 가져오자마자 내보내기를 해서 모듈를 사용할 자바스크립트에서 일일히 모듈 경로를 지정안하고 여러개의 모듈 사용가능
// utils.js
// a모듈(a.js)와 b모듈(b.js)를 export키워드로 가져오자마자 내보냄

export { a } from './a.js';
export { b } from './b.js';

// main.js
// utils.js를 import해 a모듈(a.js)와 b모듈(b.js)을 각각 가져오지않고 한번에 가져오기함

import {a, b} from './utils.js';

console.log(a());
console.log(b());




🎮 패스트캠퍼스
프론트엔드 웹 개발의 모든 것 초격차패키지 Online.