Module pattern

2024. 12. 8. 09:51·Frontend/JS Patterns

 

  • 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>
  );
}

'Frontend > 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
'Frontend/JS Patterns' 카테고리의 다른 글
  • Observer pattern
  • Mixin pattern
  • Middleware Pattern
  • Mediator Pattern
JTB
JTB
웹/앱 개발 정보를 공유하고 있습니다.
  • JTB
    JTechBlog
    JTB
  • 전체
    오늘
    어제
    • All About Programming;) N
      • Computer Science
        • Terminology and Concepts
        • Network
        • Operating System
        • Database
        • Data Structure
      • Frontend
        • Javascript Essentials
        • Perfomance Optimization
        • JS Patterns
        • Next.js
        • Flutter
      • Backend
        • Node.js
      • DevOps
        • Docker & Kubernetes
      • Coding Test N
        • LeetCode N
        • Programmers
      • Tech Books & Lectures
        • Javascript_Modern JS Deep d..
        • Network_IT 엔지니어를 위한 네트워크 입문
      • Projects
        • PolyLingo_2025
        • Build Your Body_2024
        • JStargram_2021
        • Covid19 Tracker_2021
        • JPortfolio_2021
      • BootCamp_Codestates
        • TIL
        • TILookCloser
        • Pre Tech Blog
        • IM Tech Blog
        • Daily Issues and DeBugging
        • First Project
        • Final Project
        • Sprint Review
        • Good to Know
        • Socrative Review
        • HTML &amp; CSS
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 글쓰기
    • 관리
  • 공지사항

  • 인기 글

  • 태그

    DOM
    자바스크립트 딥다이브
    Time complexity and Space complexity
    딥다이브
    need a database
    커리어
    프론트엔드 성능 최적화 가이드
    Network
    polylingo
    mobile app
    Operating System
    Binary Tree BFS
    이벤트
    스코프
    database
    js pattern
    How memory manage data
    Shared resources
    leetcode
    모던 자바스크립트 Deep Dive
    indie hacker
    structure of os
    Data Structure
    CPU scheduling algorithm
    VoiceJournal
    JavaScript
    testing
    Threads and Multithreading
    자바스크립트
    TCP/IP
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
JTB
Module pattern
상단으로

티스토리툴바