refactor(stimulus): eager load stimulus controllers
This commit is contained in:
parent
ea18c2b9ba
commit
eba1973d5f
11 changed files with 69 additions and 68 deletions
30
app/javascript/shared/stimulus-loader.ts
Normal file
30
app/javascript/shared/stimulus-loader.ts
Normal file
|
@ -0,0 +1,30 @@
|
|||
import { Application } from '@hotwired/stimulus';
|
||||
import invariant from 'tiny-invariant';
|
||||
|
||||
const controllers = import.meta.globEager('../controllers/*.{ts,tsx}');
|
||||
|
||||
export function registerControllers(application: Application) {
|
||||
for (const [path, mod] of Object.entries(controllers)) {
|
||||
const [filename] = path.split('/').reverse();
|
||||
const name = filename
|
||||
.replace(/_/g, '-')
|
||||
.replace(/-controller\.(ts|tsx)$/, '');
|
||||
if (name != 'application') {
|
||||
if (mod.default) {
|
||||
console.debug(`Registered default export for "${name}" controller`);
|
||||
application.register(name, mod.default);
|
||||
} else {
|
||||
const exports = Object.entries(mod);
|
||||
invariant(
|
||||
exports.length == 1,
|
||||
`Expected a single export but ${exports.length} exports were found for "${name}" controller`
|
||||
);
|
||||
const [exportName, exportMod] = exports[0];
|
||||
console.debug(
|
||||
`Registered named export "${exportName}" for "${name}" controller`
|
||||
);
|
||||
application.register(name, exportMod);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue