I'm building separate components for my personal portfolio using ParcelJS
I'm attaching the Project Folder Structure working tree. Also, Remainder that don't worry about public and build folder. If I run the scripts using yarn. It will automatically create the folder.
Now I have created a Header Component filename header.js
export function Header() {
return `
<nav class="nav__bar">
<button class="nav__bar__burger" onclick="ToggleClassMenu()">
<div></div>
<div></div>
<div></div>
</button>
</nav>
`;
}
Now I need to register or connect the component with an HTML file using JavaScript.
filename app.js
import { Header } from "./components/header";
function App() {
document.getElementById("nav").innerHTML = Header();
}
//Initialize the App
App();
Now I have created HTML filename index.html
Also, these codes are inside the body tag.
<noscript>You need to enable the JavaScript to run this app.</noscript>
<header class="nav" id="nav"></header>
<script src="../app.js"></script>
<script src="../app-functions.js"></script>
package.json scripts code
"scripts": {
"start": "parcel ./src/pages/*.html --out-dir public -p 3030 watch --no-cache --no-source-maps",
"build": "parcel build ./src/pages/*.html --out-dir build --public-url ./ --no-cache --no-source-maps"
}
Now I am creating for Header Component Which has a button onclick
event ToggleClassMenu function so I need to create a separate file. filename header-comps.js
export function ToggleClassMenu() {
console.log('Working Toggle Class');
}
filename app-functions.js
import "./functions/header-comps";
The problem ToggleClassMenu is undefined when someone presses the button. I don't know where I need to put the code.
If I add the code ToggleClassMenu() in the Header Component filename header.js so, still undefined when someone presses the button.
Note: I don't want this. If I add the code ToggleClassMenu() in HTML file before closing the body tag as a script tag. It is fully working fine.
Note: I want this. I want to create a separate JS file because every separate code JS file module is readable and easy to change the code. How to fix the issue ToggleClassMenu undefined.
At last, I know that we need to load the HTML document first and then javascript will be loaded.