모듈이란 ?
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