DEV Community

Bryan Ollendyke
Bryan Ollendyke

Posted on

Bonus: i18n-manager zero dependencies!

UPDATE with video, now VanillaJS!

While making these posts and the video, I realized that I really don't need to use LitElement in order to make i18n-manager work. So, after a little work today, it's not dependency free! The major changes in the code to remove LitElement invovled the following:

  • Convert static get properties() calls to get lang and set lang (so getters and setters to mirror attributes to properties)
  • Convert update life cycle to be observedAttributes and attributeChangedCallback centric
  • Replaced firstUpdated callback with connectedCallback

The update replacement looks like this:

/**
   * Life cycle
   */
  static get observedAttributes() {
    return ["lang", "dir"];
  }
  /**
   * Life cycle
   */
  attributeChangedCallback(attr, oldValue, newValue) {
    // notify of attr change
    if (attr == "lang" || attr == "dir") {
      this.dispatchEvent(
        new CustomEvent(`${attr}-changed`, {
          detail: {
            value: this[attr],
          },
        })
      );
    }
    // we are NOT moving to the default from something
    if (attr == "lang" && this[attr] && this.__ready) {
      this.updateLanguage(this[attr]);
    }
  }
Enter fullscreen mode Exit fullscreen mode

This is a good example of when to NOT use LitElement / dependencies in building web components. My general rules for when to use LitElement:

  • Does it have data reactive properties / attributes, and a lot of them?
  • Does it have a shadowRoot and will it manage a lot of value changes within it?
  • Is it doing any conditional template updating?

While LitElement is great, if you don't need to do a lot of data reactivity and NOTHING with template (i18n-manager is a non-visual singleton) then it can best serve those adopting your code to NOT have additional dependencies.

The Zero dependency method now has zero additional dependencies in the manager! So now you can work like this:

  • Make your elements, don't use the I18NMixin; just leverage the event
  • Make your localizations local to each element
  • Make your app, and reference i18n-manager early in the bootstrap
  • Everything is translatable yet all of your visual assets ship without a requirement on anything!

Top comments (1)

Collapse
 
jimmont profile image
Jim Montgomery

Great series Bryan, and excellent work, really saved me some time--thank you. Especially the zero dependencies and separation of concerns, that's exemplary.