Part 1: In my master .js file, I have a couple of shortcut functions set up:
// Selector shortcuts - mimic jQuery style selectors but using more modern, standard code
const $ = ( selector, scope = document ) => scope.querySelector( selector );
const $$ = ( selector, scope = document ) => scope.querySelectorAll( selector );
const on = ( el, type, listener ) => el.addEventListener( type, listener );
Part 2:
I'm using ES6 modules to split up the code for my site into logical, manageable chunks. Currently my local build set up is using Parcel, which I believe uses Babel to transpile the modules.
These are imported into the same master .js file in which the selector functions are defined:
// Selector shortcuts - mimic jQuery style selectors but using more modern, standard code
const $ = ( selector, scope = document ) => scope.querySelector( selector );
const $$ = ( selector, scope = document ) => scope.querySelectorAll( selector );
const on = ( el, type, listener ) => el.addEventListener( type, listener );
// Load components
import BGVideo from './BGVideo';
import FieldLabel from './FieldLabel';
// Invoke components
on( document, 'DOMContentLoaded', ( e ) => {
$$( '[data-background-video]' ).forEach( ( el ) => {
new BGVideo( el );
} );
$$( '.c-form__item' ).forEach( ( el ) => {
new FieldLabel( el );
} );
} );
These work great within the master .js file, but not within the module files - any attempt to use them triggers an error in the console e.g. Uncaught ReferenceError: $ is not defined
Is it possible access to these functions within the module files, without rewriting them at the top of every module?
Cheers