0

I am new to modules in javascript, I am trying to use function from module in none module js file - function. I am making Vanilla Js SPA.

In the bottom of - Index.html

<script type="module" src="static/js/index.js"></script>

I want to use this part in another js file in a function:

const navigateTo = url => {
  history.pushState(null, null, url); // Add the url to the history APi of Js
  router();
};

The module:

// Imports
import Dashboard from "./views/Dashboard.js";
import Posts from "./views/Posts.js";
import Settings from "./views/Settings.js";
import Register from "./views/Register.js";
import Login from "./views/Login.js";
import Profile from "./views/Profile.js";


// Navigator--------------------------------------------------------------------------------->
 const navigateTo = url => {
  history.pushState(null, null, url); // Add the url to the history APi of Js
  router();
};
                       

// Router------------------------------------------------------------------------------------>
const router = async () => {
 const routes = [
   {path: "/", view: Dashboard}, // On Path "/" use the dashboard class and inject html in the #app div
   {path: "/posts", view: Posts },
   {path: "/settings", view: Settings },
   {path: "/Register", view: Register },
   {path: "/Login", view: Login },
   {path: "/Profile", view: Profile }
 ];

 

 

 // Test each route for potential match ----------------------------------------------------->
 // Get the current Url and check if its defined in routes method "Check if its one of our Spa Urls" ----------------------------------------------------->
 const potentialMatches = routes.map(route => {
  return {
      route: route,
      isMatch: location.pathname === route.path  // true if match else false
  };
 });




// Check if there is Match------------------------------------------------------------------->
    let match = potentialMatches.find(potentialMatch => potentialMatch.isMatch);  // Get isMatch from potentialMatches


 // If no match return to StartPage
 if(!match)
 {
     match = {
     route: routes[0],
     isMatch: true
     };
 }

 const view = new match.route.view(); // If match  use the routes array of the router and get the view function for the route

 document.querySelector("#app").innerHTML = await view.getHtml();  // Get the #app div and use the view function to inject Html in it from the view class ex."Dashboard, Posts, Settings etc."
    await view.executeViewScript(); 
};





// On-Navigating-Back&Forth-Load the Content--Together with the url------------------------------------------------------------------------------------>
window.addEventListener("popstate", router); // On popstate "If back button is pressed" use the router array to load back the previeous SPA View


// Listen to document fully Loaded
document.addEventListener("DOMContentLoaded", () => {
  document.body.addEventListener("click", e => { //Listen for click in the body
    if(e.target.matches("[data-link]")){  // If body item was clicked and its data-link decorated
      e.preventDefault();  // Prevent deafult behavior dont follow the link
      navigateTo(e.target.href);  // Navigate method   
    }
  });


router(); // Load the content if the url is defined in our "Spa Urls"
});

//#### Client Routing END #####
Stefan27
  • 845
  • 8
  • 19
  • You want to do this in the frontend? You can't. You will need nodejs for this task. – Wais Kamal May 11 '21 at 19:06
  • 2
    "*I am trying to use function in none module js file*" - just don't do that. Use a module, and import the function from the other module. Alternatively, if you absolutely have to, make the function global (by assigning it to `window.router`), but I recommend not to go down this route. – Bergi May 11 '21 at 19:07
  • @WaisKamal what? no, nothing to do with nodejs. – Bergi May 11 '21 at 19:08
  • @Bergi can you import modules within the browser? – Wais Kamal May 11 '21 at 19:09
  • @WaisKamal Sure. OP is already doing it. – Bergi May 11 '21 at 19:10
  • Ok. type `import Dashboard from "./views/Dashboard.js"` into the browser console. Don't you get an error? – Wais Kamal May 11 '21 at 19:11
  • @WaisKamal OP is using ``, not the devtools console. – Bergi May 11 '21 at 19:13
  • Does it really work this way? Can you use a .js module file directly without having it go through node? Sorry but I didn't know that. – Wais Kamal May 11 '21 at 19:15
  • @Bergi - Does This means that I need to do all in modules in order to use this function - this is like chain reaction. But if I make the other js file module I probably can use the function but than other things wont work because I am using it with events onclick="" in the html and call them directly and I want to keep it. – Stefan27 May 12 '21 at 07:42
  • 1
    @Stefan27 Yes, it is recommended to go all in on modules, and to [not use inline event handler html attributes](https://stackoverflow.com/q/6941483/1048572). Putting everything in the global scope goes against the idea of modules - but it's possible if you need it for compatibility. – Bergi May 12 '21 at 11:25

1 Answers1

0

This is working window.navigate('/');

But as @BERGI recommended I did all in modules and its working even better.

Stefan27
  • 845
  • 8
  • 19