I use vanilla JavaScript to define various components in separate folders. For example, the definition for the accordion component can be found in accordion/accordion.js and is structured as follows:
import toggleCollapsible from "../../helpers/toggle-collapsible";
const SELECTOR_ACCORDION = ".accordion";
const SELECTOR_SLAT = ".accordion-slat";
function Accordion(accordion) {
...
}
Array.from(document.querySelectorAll(SELECTOR_ACCORDION)).forEach((accordion) => Accordion(accordion));
export default Accordion;
There is also an index.js file which is used only for making the component available elsewhere via export * from "./accordion";
Leaving out export default Accordion; part in accordion.js seems to work just fine. So is there any reason why I shouldn't drop it and simply use just export * from "./accordion"; in the index file?
If you don't export anything from the module, then export * from ... will also export nothing.
However, just importing that module has that side effect of activating the array for elements on the page, which feels unclean (and indeed, might not work if the script is in <head>, for instance...).
I'd wrap the Array.from() stuff in a function that's exported:
export function activateAccordions() {
Array.from(...);
}
and then import and call that in your index.
import {activateAccordions} from "./accordion";
activateAccordions(); // TODO: might need to call this only after the page is loaded
Then, if you additionally need to be able to accordion something arbitrary,
export function Accordion()
and import it too...