spartacus-storefrontangular-lazyloading

Lazy load a module that loads component using LayoutDialogConfig


I have a module that I want to lazy load and it's required only after user click a specific button. I have used Spartacus featuresModule to lazily load the module along with the LayoutConfig. However, the module is not being picked up and the get errors for missing modules that utilises it's functionality in the template.

//SpartacusFeaturesModule

@NgModule({
  declarations: [],
  imports: [...],
  providers: [SampleFeatureConfig, SampleLaunchConfig],
})
export class SpartacusFeaturesModule {
  constructor() {
    console.log('SpartacusFeaturesModule', SampleFeatureConfig);
  }
}

// SampleFeatureConfig

export const SampleFeatureConfig = provideConfig(<CustomStorefrontConfig>{
  featureModules: {
    sample: {
      module: () => import('../sample.module').then((m) => m.SampleModule),
    }
}
});

//SampleLayoutConfig

export const SampleLaunchConfig = provideConfig(<LayoutConfig>{
  launch: {
    SAMPLE: {
      inlineRoot: true,
      component: SampleComponent,
      dialogType: DIALOG_TYPE.DIALOG,
      multi: true,
    },
  },
});

//SampleModule

@NgModule({
 declarations: [SampleComponent],
 imports: [
   CommonModule,
   MatIconModule,
   MatFormFieldModule,
   MatRadioModule,
   I18nModule,
   FormsModule
 ],
 exports: [SampleComponent],
})

export class SampleModule {
  constructor() {
    console.error('[Spartacus] SampleModule loaded');
  }
}

Error:

core.mjs:6547 ERROR RuntimeError: NG0302: The pipe 'async' could not be found in the '_SampleComponent' component. Verify that it is declared or imported in this module. Find more at https://angular.dev/errors/NG0302


Solution

  • Answering my own question as I found the solution.
    this.featureModulesService.resolveFeature('featureName')

    featureModulesService is OOTB service which has resolveFeature fn that will help Spartacus trigger lazy load the feature module. Non-cms modules have no way to let Spartacus know when to load it so we'll have to do manual trigger. Hope this helps someone in future. ADIOS