In a Rails 8.1 import-map app, how does eagerLoadControllersFrom in controllers/index.js register Stimulus controllers, and when does lazyLoadControllersFrom fit better?
answer
- stimulus:install writes controllers/index.js
- reads the importmap script tag
- only *_controller pins match
- slash to --, underscore to -
- lazy loads on first data-controller
basics
~20 seagerLoadControllersFrom reads the page's import map, imports every pin under controllers/ ending in _controller and registers each under an identifier derived from its path. lazyLoadControllersFrom imports a controller only when its identifier first appears in a data-controller attribute.
solid answer
~40 s`rails new` defaults to import maps and runs `stimulus:install`, which writes `app/javascript/controllers/index.js` calling `eagerLoadControllersFrom("controllers", application)` from `@hotwired/stimulus-loading`. At boot it parses the `<script type="importmap">` JSON, keeps keys matching `controllers/…_controller`, turns each path into an identifier (strip the prefix and `_controller`, `/` to `--`, `_` to `-`), dynamically imports it and calls `application.register` unless that identifier is already registered. A file without the `_controller` suffix is silently skipped. Swapping in `lazyLoadControllersFrom` imports a controller only when a matching `data-controller` exists or later appears, watched by a `MutationObserver`: less upfront work for rarely used controllers, at the cost of a short delay before their first connect.
code
javascript · 8 lines// app/javascript/controllers/index.js (as stimulus:install writes it)
import { application } from "controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
// Lazy alternative:
// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading"
// lazyLoadControllersFrom("controllers", application)go deeper
Recall that index.js calls eagerLoadControllersFrom and that the file name, ending in _controller, decides the identifier.
Explain how the loader reads the import map, derives identifiers and registers asynchronously, and why a misnamed file fails silently.
Choose eager or lazy loading from the controller count and page usage, and diagnose registration failures with application.debug and window.Stimulus.
Decide when per-page lazy loading earns its first-use latency, and keep naming conventions strict enough that both loaders resolve every controller.
## What a new Rails 8.1 app writes `rails new` uses import maps unless you pass another `--javascript` option, and it runs `turbo:install stimulus:install`. On an import-map app, stimulus-rails 1.3.4's installer: - creates `app/javascript/controllers/application.js`, which starts the Stimulus `Application`, sets `application.debug = false` and exposes it as `window.Stimulus`; - creates `app/javascript/controllers/index.js` with three lines that import the application, import `eagerLoadControllersFrom` from `@hotwired/stimulus-loading`, and call `eagerLoadControllersFrom("controllers", application)`; - adds a sample `hello_controller.js`, an `import "controllers"` line in `application.js`, and the pins that make `controllers/...` importable (the pinning itself is the import-map setup's business). There is no list of controllers to maintain. The stimulus generator writes `app/javascript/controllers/<name>_controller.js` and, when `config/importmap.rb` exists, does **not** run `stimulus:manifest:update`, because the eager loader discovers controllers at runtime. ## How eager loading registers controllers `eagerLoadControllersFrom(under, application)` works entirely in the browser: 1. It reads the `<script type="importmap">` tag in the page and parses its `imports` JSON. 2. It keeps the keys matching `^controllers/.*_controller$`. 3. It derives an identifier from each key: strip `controllers/`, remove `_controller`, turn `/` into `--` and `_` into `-`. 4. It calls `import(path)` for each, and when the module resolves, `application.register(identifier, module.default)`. 5. It skips identifiers already registered, and logs `Failed to register controller` to the console when an import fails. | import-map key | identifier | |---|---| | `controllers/copy_link_controller` | `copy-link` | | `controllers/job_postings/character_counter_controller` | `job-postings--character-counter` | | `controllers/copy_link` | none: no `_controller` suffix, never registered | Because the imports are asynchronous, an element with `data-controller="copy-link"` may exist before its class arrives. That is fine: when `register` runs, Stimulus connects every element already carrying that identifier. An identifier with no registered controller is simply ignored, with no error, which is why a misnamed file fails silently. ## How lazy loading differs `lazyLoadControllersFrom(under, application)` registers nothing up front: - it scans the current document for `data-controller` attributes and imports only the identifiers it finds; - it keeps a `MutationObserver` on the document for new `data-controller` attributes and inserted subtrees, so a Turbo visit, frame or stream that brings a new identifier triggers its import; - it maps an identifier back to a path by reversing the rule (`--` to `/`, `-` to `_`), so `copy-link` loads `controllers/copy_link_controller`. That reverse mapping has a sharp edge: a file named `copy-link_controller.js` registers fine under eager loading but cannot be found lazily, because the lazy loader asks for `copy_link_controller`. Name files with underscores. ## Choosing between them | concern | eager | lazy | |---|---|---| | work at boot | imports every controller | imports only what the page uses | | first interaction | controller is ready once its import resolves | first use of a rare controller waits for its import | | failure mode | a broken controller logs at boot on every page | a broken controller logs only where it is used | | fit | most apps, a modest number of controllers | many controllers, most of them used on few pages | Eager loading is the generated default and the right one for most apps; lazy loading pays off when an admin area or a rarely visited editor carries heavy controllers that ordinary pages never use. Either way, a controller living outside the `controllers/` convention can be imported and registered by hand with `application.register("identifier", ControllerClass)`. ## Failure modes to recognise - **Wrong suffix.** `copy_link.js` is pinned but never registered, and the page shows no error. - **Dashes in the file name.** Works under eager loading, breaks under lazy loading. - **A different `under` prefix.** `eagerLoadControllersFrom("controllers", application)` only sees keys that start with `controllers/`; controllers pinned under another prefix need their own call or a manual `register`. - **A broken module.** A syntax or import error in one controller logs `Failed to register controller: <name> (<path>)`; the other controllers still register, so only that identifier stays inert. ## Debugging registration Setting `application.debug = true` in `controllers/application.js` logs each controller's initialize, connect and disconnect, and each action it runs, and `window.Stimulus` lets you inspect the application from the browser console, for example `Stimulus.router.modulesByIdentifier` to list registered identifiers.
- Why does the stimulus generator leave controllers/index.js alone in an import-map app?It runs `stimulus:manifest:update` only when `config/importmap.rb` is absent. With import maps, `eagerLoadControllersFrom` discovers controllers from the import map at runtime, so there is no static list of imports to regenerate.
- A new copy_link.js controller never connects and the console shows no error. What happened?The eager loader only matches import-map keys ending in `_controller`, so `controllers/copy_link` is skipped, and Stimulus ignores a `data-controller` identifier that has no registered class. Rename the file `copy_link_controller.js`.
- How do you check which controllers actually registered in the browser?Set `application.debug = true` in `controllers/application.js` to log lifecycle calls and actions, or inspect `window.Stimulus`, which the generated file assigns, for example its `controllers` list or `router.modulesByIdentifier`.
- eagerLoadControllersFrom bundles every controller into one file at build time
- A controller file without the _controller suffix still registers under its file name
- Stimulus raises an error when data-controller names an unregistered identifier
- With import maps you must run bin/rails stimulus:manifest:update after adding a controller
- lazyLoadControllersFrom finds files named with dashes as easily as underscores
Assumes Rails 8.1 with its default import maps and stimulus-rails 1.3.4 (Stimulus 3.2.2) beside Turbo 8; bundler setups use a generated index.js instead.