Skip to content

Instantly share code, notes, and snippets.

@fnando
Last active September 7, 2020 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fnando/5c4bd57b394754ac1e190e4f8343b3e1 to your computer and use it in GitHub Desktop.
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)
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