symfonywebpack-encorestimulusjs

Load Stimulus controllers from *multiple* directories in Symfony's Webpack Encore


With the default bootstrap.js (from symfony/webpack-encore-bundle) ...

import { startStimulusApp } from '@symfony/stimulus-bridge';

// Registers Stimulus controllers from controllers.json and in the controllers/ directory
export const app = startStimulusApp(require.context(
    '@symfony/stimulus-bridge/lazy-controller-loader!./controllers',
    true,
    /\.[jt]sx?$/,
));

... Stimulus controllers are loaded from assets/controllers/.

Is there a way to also load controllers from another directory?


Solution

  • Add this import to controllers.js:

    import { definitionsFromContext } from '@hotwired/stimulus-webpack-helpers';
    

    and at the bottom:

    app.load(definitionsFromContext(require.context(
        '@symfony/stimulus-bridge/lazy-controller-loader!../foo/bar/more_controllers',
        true,
        /\.[jt]sx?$/
    )));
    

    Sources: