Guenther
Guenther

Reputation: 433

Importing a list of modules in Angular?

My vision is somewhere in the lines of:

const usedModules = [MatIconModule, MatInputModule, ...];

for(let i=0; i<usedModules.length; i++) {
    import { usedModules[i] } from '@angular/material';
}
@NgModule({
    imports: usedModules,
    exports: usedModules,
})
export class AppMaterilaModule {}

Obviously this does not work. Has anybody any ideas how to create a dynamic import statement, i.e listing the usedModules only once?

Upvotes: 2

Views: 117

Answers (2)

seawave_23
seawave_23

Reputation: 1248

Modules are used for bootstrapping the application, so at that point cannot be decided what is used. The only possibility you have (which goes in this direction) is making small modules with only necessary dependencies and then using Lazy Loading, so only loading the dependencies if a certain route called. But that will lead to more time spent on page loading instead of application load. And it does not work with AOT compiling.

Upvotes: 0

v.krepkiy
v.krepkiy

Reputation: 38

You can dynamically load modules with SystemJS. It'll look like:

const plugins = [
  './plugin1.js',
  './plugin2.js'
];

const loadPlugins = (plugins) => {
  return plugins.map( (path) => window.SystemJS.import(path) );
};

Promise.all(loadPlugins(plugins)).then(() => {
    // Everything is ready now
});

I hope I understand the question right.

Upvotes: 1

Related Questions