Skip to content

Load controllers from subdirectoryΒ #44

@devsigner-xyz

Description

@devsigner-xyz

Hello, I am trying to figure out how can I create multiple bootstrap.js files and load controllers from subdirectories, the purpose of this is load only the required JS per context instead of loading all controllers everywhere. I have the feeling that I am missing something but I tried a lot of things and I can't get it to work. Example:

Originally I have bootstrap.js with this content:

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,
    /\.(j|t)sx?$/,
));

This is great, I import bootstrap.js in my entrypoints and I can use stimulus controllers everywhere, but this cause that a lots of unused JS appear in differente bundles, as you can see in the image below, mixitup and intlTelInput should not be there since I used both packages in other context but not in this one.

image

What I want to do is create bootstrap.js files per context to minimize this unused JS but I can't get to work controllers in subdirectories with stimulus-bridge.

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

export const app = startStimulusApp(require.context(
    '@symfony/stimulus-bridge/lazy-controller-loader!./controllers/landing',
    true,
    /\.(j|t)sx?$/,
));
//landing.js Encore entrypoint
import '../../bootstrap_landing';
// other landing stuff
// bootstrap_extranet.js
import { startStimulusApp } from '@symfony/stimulus-bridge';

export const app = startStimulusApp(require.context(
    '@symfony/stimulus-bridge/lazy-controller-loader!./controllers/extranet',
    true,
    /\.(j|t)sx?$/,
));
// extranet.js Encore entrypoint
import '../../bootstrap_extranet';
// other extranet stuff

By doing this, the final bundle that I have show before should be something like this:

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions