Scripting

Using custom modules for code reusability

Pro

Learn how to create and use custom modules and reuse code in your scripts.

Custom modules are a great way to reuse code. They allow you to define functions, classes, or variables in a separate file and use them in your scripts.

In this guide, we'll implement a simple e-commerce product mocking function and use modules to logically separate the code.

Code for the example page used in the video:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Product page</title>

    <style>
      html,
      body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
      }

      main {
        width: 100%;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
      }

      #product-container {
        margin-top: 20px;
        padding: 20px;
        border: 1px solid #ccc;
      }

      #product-container[data-state="loading"]::before {
        content: "Loading...";
      }

      #product-container[data-state="error"]::before {
        content: "Error loading product";
        color: red;
      }
    </style>
  </head>
  <body>
    <main>
      <h1>Product page</h1>

      <div id="product-container"></div>
    </main>

    <script>
      const productUrl = "https://my-api.dev/product";
      const productContainer = document.getElementById("product-container");

      const setState = (state) => {
        productContainer.dataset.state = state;
      };

      const displayProduct = (product) => {
        productContainer.innerHTML = `
          <p><strong>ID:</strong> ${product.id}</p>
          <p><strong>Name:</strong> ${product.name}</p>
          <p><strong>Price:</strong> ${product.price}</p>
        `;
      };

      const fetchProduct = async () => {
        try {
          setState("loading");

          const response = await fetch(productUrl, { method: "GET" });
          const data = await response.json();

          displayProduct(data);

          setState("loaded");
        } catch (error) {
          console.error(error);

          setState("error");
        }
      };

      fetchProduct();
    </script>
  </body>
</html>