Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- peerdependencies
- 이미지 갤러리 최적화
- 학습내용정리
- 자바스크립트
- 제너레이터와 async/await
- 이벤트
- 올림픽 통계 서비스 최적화
- const
- 모던 자바스크립트 Deep Dive
- 딥다이브
- package management
- mixin pattern
- 프로그래머스
- 커리어
- 프론트엔드 성능 최적화 가이드
- 스코프
- 진행기록
- js pattern
- unique identifiers
- 브라우저의 렌더링 과정
- DOM
- pr review
- 자바스크립트 패턴
- js pattern
- Babel과 Webpack
- 새 코드 받아오기
- 자바스크립트 딥다이브
- 블로그 서비스 최적화
- version management
- middleware pattern
Archives
- Today
- Total
Dev Blog
Module pattern 본문
- The module pattern allows you to split up your code into smaller, reusable pieces.
- modules allow you to keep certain values within your file private. Declarations within a module are scoped (encapsulated) to that module , by default.
// export example
export function add(x, y) {
return x + y;
}
export function multiply(x) {
return x * 2;
}
export function subtract(x, y) {
return x - y;
}
export function square(x) {
return x * x;
}
// import example
import {
add as addValues,
multiply as multiplyValues,
subtract,
square
} from "./math.js";
/* From math.js module */
addValues(7, 8);
multiplyValues(8, 9);
subtract(10, 3);
square(3);
Dynamic import
- When importing all modules on the top of a file, all modules get loaded before the rest of the file.
- In some cases, only need to import a module based on a certain condition. With a dynamic import, we can import modules on demand.
- By dynamically importing modules, we can reduce the page load time. We only have to load, parse, and compile the code that the user really needs, when the user needs it.
const button = document.getElementById("btn");
button.addEventListener("click", () => {
import("./math.js").then((module) => {
console.log("Add: ", module.add(1, 2));
console.log("Multiply: ", module.multiply(3, 2));
const button = document.getElementById("btn");
button.innerHTML = "Check the console";
});
});
Besides being able to import modules on-demand, the import() function can receive an expression. It allows us to pass template literals, in order to dynamically load modules based on a given value.
export function DogImage({ num }) {
const [src, setSrc] = React.useState("");
async function loadDogImage() {
const res = await import(`../assets/dog${num}.png`);
setSrc(res.default);
}
return src ? (
<img src={src} alt="Dog" />
) : (
<div className="loader">
<button onClick={loadDogImage}>Click to load image</button>
</div>
);
}
'Development Notes > JS Patterns' 카테고리의 다른 글
Observer pattern (0) | 2024.12.08 |
---|---|
Mixin pattern (0) | 2024.12.08 |
Middleware Pattern (0) | 2024.12.08 |
Mediator Pattern (0) | 2024.12.08 |
Flyweight Pattern (0) | 2024.12.08 |
Comments