Stimulus Discourse

Stimulus with dynamic import and webpack?

Hi guys,

To be honest, I don’t have any experience with Stimulus but I’m very interested. My biggest question right now is if there is a way to dynamically load a controller via dynamic imports and webpack only when it is actually needed (data attribute was found in the dom).

Thanks!

1 Like

Here is an example of how I am using dynamic import for large third-party libraries

 import { Controller } from "stimulus";

 export default class extends Controller {
   static targets = ["time"];

   connect() {
     import("moment").then(moment => {
       this.moment = moment.default;
       this.timer = requestAnimationFrame(this.updateTimer.bind(this));
     });
   }

   updateTimer() {
     this.timer = requestAnimationFrame(this.updateTimer.bind(this));
     this.timeTarget.textContent = this.moment().format(
       "dddd, MMMM Do YYYY, h:mm:ss a"
     );
   }

   disconnect() {
     cancelAnimationFrame(this.timer);
   }
 }

This helper library does exactly that: https://github.com/danieldiekmeier/stimulus-controller-resolver. I haven’t used it myself, but it looks solid. [via this tweet]

1 Like