Development Notes/JS Patterns
Module pattern
Nomad Kim
2024. 12. 8. 09:51
- 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>
);
}