运行时将组件或模块加载到angular2的模块中

莫滕·斯科约达格(Morten Skjoldager)

我有一个使用Typescript构建并与webpack捆绑在一起的角度应用程序。这里没什么异常。我想做的是允许运行时使用插件,这意味着捆绑包之外的组件和/或模块也应该能够在应用程序中注册。到目前为止,我已经尝试在index.html中包含另一个webpack捆绑包,并使用隐式数组将所述模块/组件推入其中,然后在我的模块中将其导入。

查看导入是否使用隐式变量。这适用于捆绑软件中的模块,但另一个捆绑软件中的模块将不起作用。

@NgModule({
  imports: window["app"].modulesImport,
  declarations: [
      DYNAMIC_DIRECTIVES,
      PropertyFilterPipe,
      PropertyDataTypeFilterPipe,
      LanguageFilterPipe,      
      PropertyNameBlackListPipe      
  ],
  exports: [
      DYNAMIC_DIRECTIVES,
      CommonModule,
      FormsModule,
      HttpModule
  ]
})
export class PartsModule {

    static forRoot()
    {
        return {
            ngModule: PartsModule,
            providers: [ ], // not used here, but if singleton needed
        };
    }
}

我还尝试过使用es5代码创建模块和组件,如下所示,并将相同的内容推送到我的modules数组中:

var HelloWorldComponent = function () {

};

HelloWorldComponent.annotations = [
    new ng.core.Component({
        selector: 'hello-world',
        template: '<h1>Hello World!</h1>',
    })
];

window["app"].componentsLazyImport.push(HelloWorldComponent);

两种方法都会导致以下错误:

ncaught Error: Unexpected value 'ExtensionsModule' imported by the module 'PartsModule'. Please add a @NgModule annotation.
    at syntaxError (http://localhost:3002/dist/app.bundle.js:43864:34) [<root>]
    at http://localhost:3002/dist/app.bundle.js:56319:44 [<root>]
    at Array.forEach (native) [<root>]
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:3002/dist/app.bundle.js:56302:49) [<root>]
    at CompileMetadataResolver.getNgModuleSummary (http://localhost:3002/dist/app.bundle.js:56244:52) [<root>]
    at http://localhost:3002/dist/app.bundle.js:56317:72 [<root>]
    at Array.forEach (native) [<root>]
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:3002/dist/app.bundle.js:56302:49) [<root>]
    at CompileMetadataResolver.getNgModuleSummary (http://localhost:3002/dist/app.bundle.js:56244:52) [<root>]
    at http://localhost:3002/dist/app.bundle.js:56317:72 [<root>]
    at Array.forEach (native) [<root>]
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:3002/dist/app.bundle.js:56302:49) [<root>]
    at JitCompiler._loadModules (http://localhost:3002/dist/app.bundle.js:67404:64) [<root>]
    at JitCompiler._compileModuleAndComponents (http://localhost:3002/dist/app.bundle.js:67363:52) [<root>]

请注意,如果我尝试使用组件而不是模块,则会将它们放在声明中,这会导致组件出现相应的错误,即我需要添加@ pipe / @ component注释。

我认为这应该可行,但我不知道自己缺少什么。我正在使用[email protected]

更新11/05/2017

因此,我决定退后一步,从头开始。而不是使用的WebPack我决定尝试用SystemJS而不是因为我发现在角的核心组件。这次我使用以下组件和服务来插入组件,使其工作:

typebuilder.ts

import { Component, ComponentFactory, NgModule, Input, Injectable, CompilerFactory } from '@angular/core';
import { JitCompiler } from '@angular/compiler';
import {platformBrowserDynamic} from "@angular/platform-browser-dynamic";

export interface IHaveDynamicData { 
    model: any;
}

@Injectable()
export class DynamicTypeBuilder {

    protected _compiler : any;
         // wee need Dynamic component builder
    constructor() {
        const compilerFactory : CompilerFactory = platformBrowserDynamic().injector.get(CompilerFactory);
        this._compiler = compilerFactory.createCompiler([]);
    }

  // this object is singleton - so we can use this as a cache
    private _cacheOfFactories: {[templateKey: string]: ComponentFactory<IHaveDynamicData>} = {};

    public createComponentFactoryFromType(type: any) : Promise<ComponentFactory<any>> {
        let module = this.createComponentModule(type);
            return new Promise((resolve) => {
            this._compiler
                .compileModuleAndAllComponentsAsync(module)
                .then((moduleWithFactories : any) =>
                {
                    let _ = window["_"];
                    let factory = _.find(moduleWithFactories.componentFactories, { componentType: type });
                    resolve(factory);
                });
        });
    }

    protected createComponentModule (componentType: any) {
        @NgModule({
        imports: [
        ],
        declarations: [
            componentType
        ],
        })
        class RuntimeComponentModule
        {
        }
        // a module for just this Type
        return RuntimeComponentModule;
    }
}

动态组件

import { Component, Input, ViewChild, ViewContainerRef, SimpleChanges, AfterViewInit, OnChanges, OnDestroy, ComponentFactory, ComponentRef } from "@angular/core";
import { DynamicTypeBuilder } from "../services/type.builder";

@Component({
    "template": '<h1>hello dynamic component <div #dynamicContentPlaceHolder></div></h1>',
    "selector": 'dynamic-component'
})
export class DynamicComponent implements AfterViewInit, OnChanges, OnDestroy {

    @Input() pathToComponentImport : string;

    @ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef}) 
    protected dynamicComponentTarget: ViewContainerRef;
    protected componentRef: ComponentRef<any>;

    constructor(private typeBuilder: DynamicTypeBuilder) 
    {

    }  

    protected refreshContent() : void {
        if (this.pathToComponentImport != null && this.pathToComponentImport.indexOf('#') != -1) {
          let [moduleName, exportName] = this.pathToComponentImport.split("#");
          window["System"].import(moduleName)
            .then((module: any) => module[exportName])
            .then((type: any) => {
                this.typeBuilder.createComponentFactoryFromType(type)
                .then((factory: ComponentFactory<any>) =>
                {
                    // Target will instantiate and inject component (we'll keep reference to it)
                    this.componentRef = this
                        .dynamicComponentTarget
                        .createComponent(factory);

                    // let's inject @Inputs to component instance
                    let component = this.componentRef.instance;

                    component.model = { text: 'hello world' };

                    //...
                });
            });
      }
    }

    ngOnDestroy(): void {
    }

    ngOnChanges(changes: SimpleChanges): void {
    }

    ngAfterViewInit(): void {
        this.refreshContent();
    }

}

现在,我可以像这样链接到任何给定的组件:

<dynamic-component pathToComponentImport="/app/views/components/component1/extremely.dynamic.component.js#ExtremelyDynamicComponent"></dynamic-component>

打字稿配置:

 {
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "allowJs": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
    "exclude": [
      "node_modules",
      "systemjs-angular-loader.js",
      "systemjs.config.extras.js",
      "systemjs.config.js"
  ]
}

在我的打字稿配置之上。这样就行了,但是我不确定我对使用SystemJS是否满意。我觉得webpack也应该有这种可能,并且不确定这是否是TC编译webpack无法理解的文件的方式...如果我尝试在webpack捆绑包中运行此代码,我仍然会遇到缺少的装饰器异常。

最好的问候莫滕

莫滕·斯科约达格(Morten Skjoldager)

所以我一直在努力寻找解决方案。最后我做到了。不管这是否是一个骇人听闻的解决方案,还有我不知道的更好的方法……现在,这就是我解决的方法。但我确实希望将来或即将出现更现代的解决方案。

该解决方案实质上是SystemJS和webpack的混合模型。在运行时中,您需要使用SystemJS来加载应用程序,并且Webpack捆绑包必须由SystemJS消耗。为此,您需要一个用于webpack的插件来使之成为可能。由于系统JS和webpack使用不同的模块定义,因此它们是不兼容的。虽然没有与此插件。

  1. 在您的核心应用和插件中,您都需要安装一个名为webpack的扩展程序

“ webpack-system-register”。

我有2.2.1版的webpack和1.5.0版的WSR。1.1在webpack.config.js中,您需要添加WebPackSystemRegister作为core.plugins中的第一个元素,如下所示:

config.plugins = [
  new WebpackSystemRegister({
    registerName: 'core-app', // optional name that SystemJS will know this bundle as. 
    systemjsDeps: [
    ]
  }) 
  //you can still use other plugins here as well
];

由于现在使用SystemJS来加载应用程序,因此您还需要一个systemjs配置。我的看起来像这样。

(function (global) {
System.config({
paths: {
  // paths serve as alias
  'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
  // our app is within the app folder
  'app': 'app',

  // angular bundles
  // '@angular/core': 'npm:@angular/core/bundles/core.umd.min.js',
  '@angular/core': '/dist/fake-umd/angular.core.fake.umd.js',
  '@angular/common': '/dist/fake-umd/angular.common.fake.umd.js',
  '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.min.js',
  '@angular/platform-browser': '/dist/fake-umd/angular.platform.browser.fake.umd.js',
  '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.min.js',
  '@angular/http': '/dist/fake-umd/angular.http.fake.umd.js',
  '@angular/router': 'npm:@angular/router/bundles/router.umd.min.js',
  '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.min.js',
  '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.min.js',
  '@angular/material': 'npm:@angular/material/bundles/material.umd.js',
  '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.min.js',
  '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.min.js',
  'angular2-grid/main': 'npm:angular2-grid/bundles/NgGrid.umd.min.js',      
  '@ng-bootstrap/ng-bootstrap': 'npm:@ng-bootstrap/ng-bootstrap/bundles/ng-bootstrap.js',            
  // other libraries
  'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js', 
  "rxjs": "npm:rxjs",          


},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
  app: {
    defaultExtension: 'js',
    meta: {
      './*.html': {
        defaultExension: false,
      },
      './*.js': {
        loader: '/dist/configuration/systemjs-angular-loader.js'
      },
    }
  },
  rxjs: {
    defaultExtension: 'js'
  },
},
  });
 })(this);

稍后,我将在答案中返回map元素,描述为什么在其中存在角度以及如何完成角度。在index.html中,您需要像这样引用:

<script src="node_modules/systemjs/dist/system.src.js"></script> //system
<script src="node_modules/reflect-metadata/reflect.js"></script>
<script src="/dist/configuration/systemjs.config.js"></script> // config for system js
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/dist/declarations.js"></script> // global defined variables
<script src="/dist/app.bundle.js"></script> //core app
<script src="/dist/extensions.bundle.js"></script> //extensions app

目前,这使我们可以根据需要运行所有内容。但是,这样做有一点曲折,那就是您仍然会遇到原始帖子中所述的异常。要解决此问题(尽管我仍然不知道为什么会这样),我们需要对使用webpack和webpack-system-register创建的插件源代码做一个技巧:

plugins: [
  new WebpackSystemRegister({
      registerName: 'extension-module', // optional name that SystemJS will know this bundle as. 
      systemjsDeps: [
        /^@angular/,
        /^rx/
      ]
  })

上面的代码使用webpack系统寄存器从扩展捆绑包中排除Angular和RxJs模块。将会发生的是,导入模块时,systemJS将遇到angular和RxJs。它们被忽略了,因此System将尝试使用System.config.js的映射配置来加载它们。现在来了有趣的部分:

在核心应用程序中,在webpack中,我导入所有angular模块并将其公开到公共变量中。这可以在您的应用程序中的任何地方完成,我已经在main.ts中完成了。下面给出示例:

lux.bootstrapModule = function(module, requireName, propertyNameToUse) {
    window["lux"].angularModules.modules[propertyNameToUse] = module;
    window["lux"].angularModules.map[requireName] = module;
}

import * as angularCore from '@angular/core';
window["lux"].bootstrapModule(angularCore, '@angular/core', 'core');
platformBrowserDynamic().bootstrapModule(AppModule);

在我们的systemjs配置中,我们创建了一个这样的映射,以使systemjs知道将我们的依赖商品加载到何处(如上所述,它们在扩展束中是不包括在内的):

'@angular/core': '/dist/fake-umd/angular.core.fake.umd.js',
'@angular/common': '/dist/fake-umd/angular.common.fake.umd.js',

因此,每当systemjs遇到角核或角公共点时,都会被告知从我定义的伪umd捆绑包中加载它。他们看起来像这样:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define([], factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS-like
        module.exports = factory();
    }
}(this, function () {

    //    exposed public method
    return window["lux"].angularModules.modules.core;
}));

最终,使用运行时编译器,我现在可以使用从外部加载的模块:

因此,系统现在可以在Angular中用于导入和编译模块。每个模块只需执行一次。不幸的是,这使您无法省去繁重的运行时编译器。

我有一项服务,可以加载模块并返回工厂,最终使您能够延迟加载内核中不知道的模块对于商业平台,CMS,CRM系统之类的软件供应商,或其他开发人员无需源代码即可为此类系统创建插件的软件供应商而言,这非常有用。

window["System"].import(moduleName) //module name is defined in the webpack-system-register "registerName"
            .then((module: any) => module[exportName])
            .then((type: any) => {
                let module = this.createComponentModuleWithModule(type);
                this._compiler.compileModuleAndAllComponentsAsync(module).then((moduleWithFactories: any) => {
                    const moduleRef = moduleWithFactories.ngModuleFactory.create(this.injector);

                    for (let factory of moduleWithFactories.componentFactories) {

                        if (factory.selector == 'dynamic-component') { //all extension modules will have a factory for this. Doesn't need to go into the cache as not used.
                            continue;
                        }

                        var factoryToCache = {
                            template: null,
                            injector: moduleRef.injector,
                            selector: factory.selector,
                            isExternalModule: true,
                            factory: factory,
                            moduleRef: moduleRef,
                            moduleName: moduleName,
                            exportName: exportName
                        }

                        if (factory.selector in this._cacheOfComponentFactories) {
                            var existingFactory = this._cacheOfComponentFactories[factory.selector]
                            console.error(`Two different factories conflicts in selector:`, factoryToCache, existingFactory)
                            throw `factory already exists. Did the two modules '${moduleName}-${exportName}' and '${existingFactory.moduleName}-${existingFactory.exportName}' share a component selector?: ${factory.selector}`;
                        }

                        if (factory.selector.indexOf(factoryToCache.exportName) == -1) {
                            console.warn(`best practice for extension modules is to prefix selectors with exportname to avoid conflicts. Consider using: ${factoryToCache.exportName}-${factory.selector} as a selector for your component instead of ${factory.selector}`);
                        }

                        this._cacheOfComponentFactories[factory.selector] = factoryToCache;
                    }
                })
                resolve();
            })

把它们加起来:

  1. 在您的核心应用和扩展模块中都安装webpack-system-register
  2. 在扩展束中排除角度依赖性
  3. 在您的核心应用程序中公开全局变量中的角度依赖性
  4. 通过返回公开的依赖关系,为每个依赖关系创建伪造的捆绑包
  5. 在您的systemjs映射中,添加要在假js捆绑包中加载的依赖项
  6. Angular中的运行时编译器现在可用于使用webpack-system-register加载与webpack打包在一起的模块

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Angular 2 组件未加载到不同的模块中

Angular2:将节点模块加载到使用Angular-CLI构建的组件中时,如何解决404错误

在运行时重新加载模块

Angular2在运行时将AppModule的服务注入到依赖的NgModule的组件中吗?

Angular模块的forRoot中的运行时值

Angular 5-在运行时动态加载模块(在编译时未知)

Angular 8和惰性模块未加载运行时编译器

如何在运行时重新加载所需的模块?

如何在运行时加载模块?

将表的数据加载到运行时创建的 DataGridView

Angular2无法识别导入模块中的组件

在 angular2 组件中需要节点模块

在多个模块中声明的Angular2组件

在Electronic App中运行时加载Node.js模块

Android在运行时将数据加载到表布局中

规格文件中的组件声明,而不是将顶级模块加载到TestBed中

如何检查或证明angular2中的模块是延迟加载的?

Angular2访问子模块组件

Angular2:模块和组件的区别

Angular2 组件或模块 npm 包

Angular2从模块导入组件/服务

在 angular4 中将 json 加载到组件中时找不到模块

将组件加载到路由器插座而不在任何模块中声明它

运行运行时捆绑包后,iis模块中缺少aspnetcoremoduleV2

Angular2-从模块动态加载组件

Angular,在延迟加载的模块中暴露组件

angular2:如何在运行时创建的组件上使用EventEmitter?

Angular2延迟加载模块错误'找不到模块'

Ionic 2-运行时错误找不到模块“。”