esbuild-plugin-stimulus

raw JSON →
0.2.0 verified Mon Apr 27 auth: no javascript

An esbuild plugin for automatically loading Stimulus controllers from a folder, inspired by the webpack helpers. Version 0.2.0 is current and stable. It maps controller file names to Stimulus identifier conventions (e.g., `users/list_item_controller.js` becomes `users--list-item`). Ships TypeScript declarations. No breaking changes known, but usage requires both esbuild and Stimulus (or @hotwired/stimulus). Lightweight, single-purpose plugin with no runtime dependencies.

error TypeScript error: Cannot find module 'stimulus:./controllers' or its corresponding type declarations.
cause Missing type declaration file for the virtual module.
fix
Add a esbuild-plugin-stimulus.d.ts file (as shown in the quickstart) to your project.
error Error: [esbuild] Plugin 'stimulus' returned an error: Could not resolve 'stimulus:./controllers'
cause The stimulus plugin is not included in the esbuild plugins array.
fix
Add stimulusPlugin() to the plugins array in your esbuild configuration.
gotcha Plugin requires the `stimulus:` import prefix to work; using a bare path will not trigger the plugin.
fix Always use `from 'stimulus:./controllers'` (with the prefix) in your application code.
gotcha The import path in `stimulus:./controllers` is relative to the project root (where esbuild is invoked), not relative to the importing file.
fix Ensure the path after `stimulus:` resolves from your project root. For example, if your app is in `src/app.js` and controllers in `src/controllers`, use `'stimulus:./src/controllers'`.
deprecated If you are using the older 'stimulus' package (before it was renamed to @hotwired/stimulus), the import paths may still work, but it is recommended to update.
fix Replace `import { Application } from 'stimulus'` with `import { Application } from '@hotwired/stimulus'`.
npm install esbuild-plugin-stimulus
yarn add esbuild-plugin-stimulus
pnpm add esbuild-plugin-stimulus

Sets up esbuild with the plugin and uses the virtual module to load controllers from the ./controllers directory.

// build.js (CommonJS)
const esbuild = require('esbuild');
const { stimulusPlugin } = require('esbuild-plugin-stimulus');

esbuild.build({
  entryPoints: ['app.js'],
  bundle: true,
  outfile: 'dist/bundle.js',
  plugins: [stimulusPlugin()],
}).catch(() => process.exit(1));

// app.js (ESM)
import { Application } from '@hotwired/stimulus';
import { definitions } from 'stimulus:./controllers';

const app = Application.start();
app.load(definitions);

// esbuild-plugin-stimulus.d.ts (optional, for TypeScript)
declare module 'stimulus:*' {
  import type { Definition } from '@hotwired/stimulus';
  export const definitions: Definition[];
}