javascriptfunctionimportmoduleexport

Import JS function from another file doesnt work


im doing a little project for my own to my portfolio. Im a beginner programmer and i have a problem with import function js from another file. This function is necessary because i need this to use in another logic of my code. These two files are in the same folder named scripts. Scripts are added to index.html before the body closing tag with defer attibute.

ProductsDb.mjs:

import axios from "axios";

const productsDb = process.env.DB_BASE_URL;
let products;

export const fetchProducts = async () => {
  const productsDb = process.env.DB_BASE_URL;
  try {
    const res = await axios.get(productsDb);
    products = res.data;
    //console.log("value of products:", products);
    return products;
  } catch (err) {
    console.err("Error fetching products: ", err);
    throw err;
  }
};
const createProductCart = async () => {
  await fetchProducts();
  const shopList = document.querySelector(".shop-list");
  shopList.innerHTML = "";
  console.log(products);

  products.forEach((element) => {
    const shoppingCart = document.createElement("li");
    shoppingCart.classList.add("shop-list-item");

    let imgURL = `http://127.0.0.1:3000${element.image}`;
    shoppingCart.innerHTML = `
        <a href="#">
          <img class="item-image" height="320px" width="320px" src="${imgURL}" alt="${element.name}" />
          <div class="shop-list-info">
            <p>${element.category}</p>
            <h3>${element.name}</h3>
          </div>
        </a>
        <button class="openCartModal" data-id="${element.id}">Wybierz opcje</button>
      `;

    shopList.appendChild(shoppingCart);
  });
  return;
};

document.addEventListener("DOMContentLoaded", async () => {
  try {
    createProductCart();
  } catch (err) {
    console.error("Error", err);
  }
});

modal.mjs:

import { fetchProducts } from "./productsDb.mjs";

// Open quick shopping modal window
const shopList = document.querySelector(".shop-list");
shopList.addEventListener("click", function (ev) {
  const modal = document.querySelector("[modalOpen]");
  const modalClose = document.querySelector("[modalClose]");

  if (ev.target.closest(".openCartModal")) {
    openModal(modal, modalClose);
  }
});

function openModal(modal, modalClose) {
  modal.classList.toggle("isHidden");

  function close() {
    modal.classList.toggle("isHidden");
    document.removeEventListener("keydown", keyClose);
    modal.removeEventListener("click", clickOutClose);
    modalClose.removeEventListener("click", close);
  }

  function keyClose(ev) {
    if (ev.key === "Escape" && !modal.classList.contains("isHidden")) {
      close();
    }
  }

  function clickOutClose(ev) {
    if (ev.target === modal || ev.target.classList.contains("isHidden")) {
      close();
    }
  }
  document.addEventListener("keydown", keyClose);
  modal.addEventListener("click", clickOutClose);
  modalClose.addEventListener("click", close);
}

I need to use the fetchProducts function in modal logic to pass value from database to the opening modal. Im trying change my script type to module, also in package.json changing type to module but with no positive results. When Im restarting my frontend only the name of module in console changing every each of time.

I receive that something like that:

Uncaught Error: Cannot find module '92Na4'
    at newRequire (kk-js.6bb1462e.js:74:19)
    at newRequire (kk-js.57740558.js:66:18)
    at newRequire (kk-js.8b89b8d5.js:66:18)
    at newRequire (kk-js.8b89b8d5.js:58:18)
    at localRequire (kk-js.8b89b8d5.js:97:35)
    at fsaaM../productsDb.mjs (modal.mjs:1:1)
    at newRequire (kk-js.8b89b8d5.js:84:24)
    at kk-js.8b89b8d5.js:144:5
    at kk-js.8b89b8d5.js:163:3

Any ideas will be very helpful for me.


Solution

  • A quick fix of this problem would be to just remove the module type of the scripts and calling the method fetchProducts() in modal.mjs. You just need to make sure that you don't export the function anymore and both js-files are added in the HTML-Body, the file where the function is defined (ProductsDb.mjs) before the one you want to use it in. You then would also need to use the not modular import() for the "axios" or also include it in the body if it's an script