Last active
September 7, 2020 20:56
-
-
Save fnando/5c4bd57b394754ac1e190e4f8343b3e1 to your computer and use it in GitHub Desktop.
Loading Stimulus.js controllers without `@stimulus/webpack-helpers` (no `_controller` suffix, no need to default export classes)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Application } from "stimulus"; | |
import "style/main.css"; | |
const application = Application.start(); | |
const context = require.context("./controllers", true, /\.[jt]s$/); | |
// Let's not follow stimulus' default name pattern. | |
// Instead, files can be named just as the controller. E.g. if your controller | |
// is called `RefreshPanel`, your source file would be | |
// `controllers/RefreshPanel.ts`, and your `data-controller` attribute would be | |
// `refreshPanel`. | |
context.keys().forEach((path) => { | |
const controllerName = path.replace(/^\.\/(.*?)\.[jt]s$/, "$1"); | |
// eslint-disable-next-line @typescript-eslint/no-var-requires | |
const module = require(`./controllers/${controllerName}`); | |
const controller = module[controllerName]; | |
const logicalName = controllerName[0].toLowerCase() + controllerName.substr(1); | |
application.register(logicalName, controller); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment