모듈

현성·2023년 12월 4일
0

모듈이란 ?

  • 모듈(Module)이란 특정 데이터들의 집합(파일)입니다.
  • 모듈 가져오기(Import), 내보내기(Export)

module.js

export const hello = "Hello world!";

main.js

import { hello } from "./module";

console.log(hello); // Hello world!

module.js

// 기본 내보내기
// default 키워드는 하나의 모듈에 한 번만 사용할 수 있습니다.
export default 123;

// 이름 내보내기
export const str = "ABC";
export const arr = [];
export const hello = () => {
  console.log("Hello world!");
};

main.js

import number, { str, arr, hello } from "./module.js";

console.log(number); // 123
console.log(str, arr); // ABC []
hello(); // Hello world!

이름 내보내기의 변수명 바꾸기

  • import구문에 as키워드를 사용하여 변수명을 바꿀 수 있습니다.

module.js

// 기본 내보내기
export default 123;

// 이름 내보내기
export const str = "ABC";
export const arr = [];
export const hello = () => {
  console.log("Hello world!");
};

main.js

import { str as xyz, arr, hello as h } from "./module.js";

console.log(xyz);
console.log(arr);
console.log(h);

모든 데이터 가져오기

module.js

// 기본 내보내기
export default 123;

// 이름 내보내기
export const str = "ABC";
export const arr = [];
export const hello = () => {
  console.log("Hello world!");
};

main.js

import * as abc from "./module.js";

console.log(abc);

동적으로 모듈 가져오기

  • import구문은 항상 모듈의 최상단에 작성되어져 있어야 합니다.
    그렇기 때문에 setTimeout함수 안에 작성할 수 없고 import함수를 사용합니다.

module.js

// 기본 내보내기
export default 123;

// 이름 내보내기
export const str = "ABC";
export const arr = [];
export const hello = () => {
  console.log("Hello world!");
};

main.js

setTimeout(() => {
  import("./module.js").then((abc) => {
    console.log(abc);
  });
}, 1000);
  • 이런식으로 작성도 가능합니다.
setTimeout(async () => {
  const abc = await import("./module.js");
  console.log(abc);
}, 1000);

가져온 모듈 바로 내보내기

a.js

export const a = () => 123;

b.js

export const b = () => 456;

utils.js

export { a } from "./a";
export { b } from "./b";

main.js

import { a, b } from "./utils";

console.log(a()); // 123
console.log(b()); // 456
profile
👈🏻 매일 꾸준히 성장하는 개발자 !

0개의 댓글