Registering Stimulus Controllers

I’ve started using Stimulus recently and I really love it so far.

Somewhere I ran across the following syntax:

application.register('hello', class extends Stimulus.Controller {

That works really well for me and I like the self-registering aspect of it.

The documentation uses the following syntax:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

But I can’t get that to work for me. I get an error of “The specifier “@hotwired/stimulus” was a bare specifier, but was not remapped to anything.”. My Google on this turns up stuff about Rails, which I’m not using.

Is there a reason to use one syntax over the other? Should I be using the syntax from the documentation if I want to work well with others? If so, how?

Thanks so much for any help!

Hi sebtools, the second one is the usual.

What environment are you working in?

Usually you have a file like a application.js which holds all the initializers where the register happens.

I wrote the npm package stimulus-initializer.

This gets the identifier from the filename, for example, you make a file like hello-controller.js and it pulls the hello from the filename, by mapping all files within a specific folder by the *-controller.js.

But if you are on vite there are helpers like vite-rails-helpers that contains similar initializers.

I’m doing some stuff in straight HTML (mostly as learning exercises) and some stuff with a ColdFusion back-end.

Does that mean that I have to either register every component I have on every page or have separate registration on each page based on what I need?

What’s the advantage of this approach over self-registering components?

I realize that sounds like I am being sarcastic, but I intend it as a genuine question. I’m still trying to learn the “Stimulus way” of doing things.

Does the self-registering syntax get in the way of extending components?

To use the second syntax, what do I need to load before the controller? It may have been obvious from the documentation, but I did read it a few times and failed to grasp it.

Thanks so much!