Sage 9 JS modules method/approach

Hi all,

I’m interested to hear how you are using ES6 modules with Sage 9.

I keep going back and forth on the best method/approach, which may be more ES6 specific, but I’m keen to hear your thoughts.

I’ve tried the new ES6 “Classes”, but I’m not a fan simply due to the issues that arise around this and event handling, having to bind each of the functions to the event handler.

Lately I’ve been doing the following, creating a folder called comps/ within scripts/ (keep in mind this for small/medium sized sites), and then exporting the function names I want to expose.

Basic example for a hamburger nav;

comps/navIcon.js

import $ from 'jquery';

const $el = $('[data-js="nav-icon"]');

function toggle(event) {
  event.preventDefault();
  $el.toggleClass('is-active');
}

function listen() {
  $el.on('click', toggle);
}

export default {
  listen,
}

I then use the route, in this case common.js to use within the view.

import nav from '../comps/navIcon';

export default {
  init() {
    nav.listen();
  },
};

This seems to be the simplest approach without dealing with prototypal inheritance or Classes. Only the function listen() is accessible from outside the module, but it still has access to local variables/functions within the module.

It seems too good to be true though, so I’m wondering if I’m overlooking something here?

How are you managing/writing your JavaScript modules?

3 Likes

I do this but that’s because you told me too :grin:

1 Like

Haha! So far it’s working well, just wanted to hear how others are doing it.