Angular 5 - load modules (that are not known at compile time) dynamically at run-time

前端 未结 2 1867
半阙折子戏
半阙折子戏 2020-12-30 15:28

Is it possible for Angular 5 to load modules/components that are not known at compile time, but during runtime dynamically?

I guess this won\'t work using webpack bu

相关标签:
2条回答
  • 2020-12-30 15:33

    You could look at Dynamic Component Loading: https://angular.io/guide/dynamic-component-loader

    It allows you to add components dynamically at runtime.

    0 讨论(0)
  • 2020-12-30 15:38

    Well, while there are complexities involved, you could try it. Depends on your code base I guess. The router exposes config property, holding its current config, and a resetConfig(routes: Routes) method for reseting configuration. You can start from there, and add, say, components on the fly.

    The components do have to be reachable, though. Perhaps dynamically created, as mentioned in the other answer. Alternatively, your config could include something like this:

    constructor(private router: Router) {}
    
    private addPlugin(routePath, pluginName, pluginPath) {
        const currentConfig = this.router.config;
        currentConfig.push({
            path: routePath,
            loadChildren: `precompiled-modules/${pluginPath}#${pluginName}`,
        });
        this.router.resetConfig(currentConfig);
    }
    

    You would have to get the pluginPath and pluginName somehow - maybe calculate it by convention, maybe a lil' backend helper that gets this, maybe have the array of it preconfigured and already loaded or similar. I also assume you would have a really good test system, to make sure your plugins are "compatible". And finally, teach webpack/systemjs how to have the modules ready. All in all, it is not impossible, but it involves some groundwork.

    That said, Angular 6 is around the corner, and with it, Angular Elements. Elements will provide a way to compile your modules as web components and "export" them, so that they can get used anywhere (not necessarily in Angular apps). Think jQuery plugins - there is a base jQuery.min.js you need to have loaded, but apart from that you don't think about it any more, you just use your new elements. It's similar with Angular Elements - you export what is basically a Web component. There is a "loader" part (jquery.min.js equivalent), and your Element bundle. But then your component is just another HTML node, with properties, attributes, bindings, events, you don't care any more, just like you don't about inputs.

    It might be worth the wait, take a look and decide for yourself.

    0 讨论(0)
提交回复
热议问题