Angular 7.0.3 CLI-从Webpack捆绑包动态加载外部模块

时间:2018-11-14 01:00:09

标签: angular webpack dynamic angular-cli bundle

我有两个Angular 7.0.3 cli应用程序。当我导航到特定路线时,我想从代理服务器获取第二个应用程序作为外部Webpack捆绑并将其安装在我的主应用程序上。

具体来说,我在理解我需要多么精确地设置我的angular.json和/或自定义webpack.config文件(如果我需要一个)的麻烦,以便我可以提供一个捆绑包。另外,我不太确定如何处理CustomModuleLoader.load()函数。

某些背景:

我正在使用APP_INITIALIZER来获取一个配置,其中包含有关需要动态添加哪些路由的数据。我用新值重置配置。可以说我的第二个应用程序正在处理客户页面:

{ provide: APP_INITIALIZER, useFactory: (myCustomServiceFactory: SomeService) => () => myCustomServiceFactory.get(), deps: [SomeService], multi: true },

服务:

    get() {
        return this.http.get(this.url)
            .toPromise()
            .then((body: DataApiResponseMessage) => {
                let router = this.injector.get(Router);
                let routeArray: Route[] = [];
                //example route
                let route: Route = {
                    path: 'clients',
                    loadChildren: '@myapp/clients#ClientsModule'
                };
                routeArray.push(route);
                router.resetConfig([...routeArray, ...router.config]); 
            })
            .catch((error) => this.handleError(error))
    }

导航到“ / clients”后,我从第二个应用程序中请求外部捆绑包:

app.use('/@myapp/clients', function (req, res) {
    apiProxy.web(req, res, { target: 'http://localhost:3001' });
});

我的第二个应用程序响应dist / main.js

res.sendFile(path.resolve(process.cwd(), 'dist/main.js'));

我的CustomModuleLoader:

import { Injectable, Injector, Compiler, NgModuleFactoryLoader, 
NgModuleFactory } from '@angular/core';

const SEPARATOR = '#';

@Injectable()
    export class CustomModuleLoader implements NgModuleFactoryLoader {
    constructor(private compiler: Compiler, private injector: Injector) {

    }

    load(path: string): Promise<NgModuleFactory<any>> {
        let [url, moduleName] = path.split(SEPARATOR);

        return this.loadScript(url).then(() => {
            //build and return ngModuleFactory here from
            //@myapp/clients bundle.js file or window (?)
        }).catch((err) => {
            console.log(err);
        });
    }

    loadScript(url) {
        return new Promise((resolve, reject) => {
            var script = document.createElement('script');
            var body = document.getElementsByTagName('body')[0];
            script.src = url;
            script.charset = "UTF-8";
            script.onload = function () {
                resolve();
            }
            script.onerror = function () {
                reject();
            }
            body.appendChild(script);
        });
    }
}

在第二个应用程序中,我正在使用@angular-builders/custom-webpack:browser并声明customWebpackConfig。我有一个(为空,因为我不太确定要在其中放置什么)webpack.config.js文件,在该文件中我将angular和其他主要库声明为外部文件并输出一个bundle.js文件。

我需要什么样的angular.json / webpack.config.js配置才能正确提供第二个应用程序?然后,如何在CustomModuleLoader.load()函数中的主应用程序中将Webpack捆绑包作为ngModule挂载?

0 个答案:

没有答案
相关问题