Patterns and best practices for trivial JS or simple DOM manipulation in Webpacker?

For projects where most existing JS is a matter of minor bits of JQuery DOM-manipulation, tightly bound to views, attempts to abstract out JS into proper modules can seem forced or counterproductive. To my mind, putting such things into packs looks a bit wrong, leaving it inline looks messy, and leaving it to sprockets but allotting more substantial JS to webpacker also seems messy. Presumably lots of people in the Rails world are grappling with this question at the moment. I would be interested to know what solutions people have settled on. Is there any sense of an orthodox “best practice” emerging?

1 Like

You might want to take a look at Stimulus, which adds just enough structure and works well with webpacker. I haven’t really looked elsewhere since I started using it.


Solutions for our case was - invest the time and set up webpacker and stimulus and start moving away from sprockets for js. Then each time you touch a js you migrate it to Stimulus. It worked perfectly. We’ve reduced the time we spend on JS as a whole to a fraction of what we were doing. But it took time.

Most of ourStimulus controllers are quite simple. 2-3 methods, not more than 20 lines for the whole controller as a whole.

1 Like