-
Notifications
You must be signed in to change notification settings - Fork 0
Javascript Guide
Javascript in Base Build projects is written to be modular and component forward. This means that JS is written in a non-monolithic file structure with small discreet related bits of code being contained in separate files and import
ed to a central main.js file.
In the assets folder there is a JS
directory that contains several JS files as well as some directories. This folder is where you will find the main.js
file that acts as the hub for JS in the build. The file consists of an imports section:
import accessibleMenu from "../../views/organisms/header/display/accessible-menu";
import mobileMenu from "../../views/organisms/header/display/mobile-menu";
import skipLinkFocusFix from "../../views/organisms/header/display/skip-link-focus-fix";
As well as an asynchronous init
function:
async function init() {
/* Load JS for blocks only if they exist on the page */
/* https://parceljs.org/features/code-splitting/ */
/* Accordion */
const accordionsList = document.querySelector(".accordion");
if (accordionsList) {
const accordionsJS = await import( '../../views/organisms/blocks/accordion/display/accordion' );
accordionsJS.render();
}
... and so on
The init function checks for the presence a component using a querySelector
call and check if that's truthy or not. If there is a component found it will then import the JS and call its export
ed render
function. The render
function is part of Parcel's system and is documented in the "how it works" section.
To add a new entry to the init
function you can follow the existing syntax of querying for the component then importing and rendering the JS only if it's available on the page.
Component JS is stored in the views
directory in the same display
directory as the template markup for the component. This is to ensure that code that supports other code is related by location.
To this end it is using Parcel's Code Splitting functionality to pull in JS only when a component is found on the page.