Coder Social home page Coder Social logo

module-loading's Introduction

module-loading

If you're looking at using this then I highly suggest hold out a little long till you can use Angular Elements, theyr'e a far better fit this this kind of situation. See here for a small demo on what they are: https://www.youtube.com/watch?v=ljsOPm4MMEo
or use another form of dynamic content that you can find out about here: https://www.youtube.com/watch?v=__H65AsA_bE&feature=youtu.be&t=2h14m13s
and demo here: https://stackblitz.com/edit/angular-dynamic-content-viewer


This repo has 2 examples of how to dynamically load Modules in Angular

Static

This shows how you can load in a module similar to how @angular/router does.
Here we require the module to be known at build time.
Do note that it also makes use of a private API on this line

const compType = moduleFactories['LazyCompNgFactory']._componentType;

Noted by the _, do not use this API unless you want to risk it being broken in the future since private API's are not subject to any of Angular's policies on breaking changes.
This is mainly for comparison to the more dynamic way.

Dynamic

This is the main feature of this repository.
Here the plugin (Angular module) does not need to be known at build time for the main application to be built.
With this method you can make plugins independantly of the main application.
This is accomplished through the use of Webpack and Rollup and externalising dependencies.
However, the issue with doing this is that all your dependencies must be loaded in as UMD bundles, which means that you loose all global optimisations. Meaning that you wont be able to do tree shaking or similar optimisations.

If you have any questions feel free to make an issue or ping on on Gitter with @Toxicable

module-loading's People

Contributors

angular-cli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

module-loading's Issues

Not loading module on angular 4.4.6 and/or 5.0.1

I created an umd library using rollup and angular 5.
I modified your code to load my own library and Everythings works, but integrating your code in my project I have a troubble on this part.

`
// ANGULAR
import { Component, ComponentFactory, ComponentFactoryResolver, Injector, Input, NgModuleFactory, NgModuleRef, OnInit, ViewContainerRef, ViewChild } from '@angular/core';

// CLASSES
import { MetadataModule } from '../../classes/metadata-module';
import { ModuleData } from '../../classes/module-data';

// SERVICES
import { ModuleService } from '../../services/module.service';

@component({
selector: 'dynamic-component-loader',
template: ''
})
export class DynamicLoaderComponent implements OnInit {

@input('moduleData') moduleData: ModuleData;
private factorySuffix: string = 'NgFactory';
private pluginEntryPointToken: string = 'PLUGIN_ENTRY_POINT';

constructor(
private injector: Injector,
private _resolver: ComponentFactoryResolver,
private moduleService: ModuleService,
private viewRef: ViewContainerRef,
) { }

ngOnInit() {
console.log('DynamicLoaderComponent ngOnInit');
console.log(this.moduleData);

this.moduleService.loadMetadataFile(this.moduleData.metadata)
  .subscribe((metadataModule: MetadataModule) => {
    console.log(metadataModule);
    const script: HTMLScriptElement = document.createElement('script');
    script.src = this.moduleData.library;
    script.onload = () => {
      console.log('script loaded');
      const moduleFactory: NgModuleFactory<any> = window[metadataModule.name][metadataModule.moduleName + this.factorySuffix];
      const moduleRef: NgModuleRef<any> = moduleFactory.create(this.injector);
      const compType = moduleRef.injector.get(this.pluginEntryPointToken);
      const compFactory: ComponentFactory<any> = moduleRef.componentFactoryResolver.resolveComponentFactory(compType);
      this.viewRef.createComponent(compFactory);
    };
    document.head.appendChild(script);
  });

}

}

`

ERROR Error: StaticInjectorError[RendererFactory2]:
StaticInjectorError[RendererFactory2]:
NullInjectorError: No provider for RendererFactory2!
at _NullInjector.webpackJsonp../node_modules/@angular/core/esm5/core.js._NullInjector.get

this is my repo: https://github.com/xino1010/angular-external-modules

Run time failure

zone.js:2933 GET http://localhost:4200/assets/plugins/myplugin-cli/plugin-metadata.json 404 (Not Found)
scheduleTask @ zone.js:2933
ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ long-stack-trace-zone.js:117
ZoneDelegate.scheduleTask @ zone.js:405
onScheduleTask @ zone.js:301
ZoneDelegate.scheduleTask @ zone.js:405
Zone.scheduleTask @ zone.js:236
Zone.scheduleMacroTask @ zone.js:259
(anonymous) @ zone.js:2966
proto.(anonymous function) @ zone.js:1366
(anonymous) @ xhr_backend.ts:156
Observable.trySubscribe @ Rx.js:1237
Observable.subscribe @ Rx.js:1225
MapOperator.call @ Rx.js:6167
Observable.subscribe @ Rx.js:1222
MapOperator.call @ Rx.js:6167
Observable.subscribe @ Rx.js:1222
webpackJsonp.43.DynamicComponentLoader.ngOnInit @ dynamic-plugin-loader.component.ts:51
checkAndUpdateDirectiveInline @ provider.ts:276
checkAndUpdateNodeInline @ view.ts:519
checkAndUpdateNode @ view.ts:462
debugCheckAndUpdateNode @ services.ts:389
debugCheckDirectivesFn @ services.ts:476
(anonymous) @ AppComponent.html:2
debugUpdateDirectives @ services.ts:455
checkAndUpdateView @ view.ts:375
callViewAction @ view.ts:770
execComponentViewsAction @ view.ts:703
checkAndUpdateView @ view.ts:432
callWithDebugContext @ services.ts:829
debugCheckAndUpdateView @ services.ts:397
ViewRef
.detectChanges @ refs.ts:441
(anonymous) @ application_ref.ts:713
ApplicationRef_.tick @ application_ref.ts:713
ApplicationRef_.loadComponent @ application_ref.ts:560
ApplicationRef
.bootstrap @ application_ref.ts:550
(anonymous) @ application_ref.ts:415
PlatformRef_.moduleDoBootstrap @ application_ref.ts:415
(anonymous) @ application_ref.ts:371
ZoneDelegate.invoke @ zone.js:392
onInvoke @ ng_zone.ts:296
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
(anonymous) @ zone.js:873
ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ ng_zone.ts:288
ZoneDelegate.invokeTask @ zone.js:424
Zone.runTask @ zone.js:192
drainMicroTaskQueue @ zone.js:602
Promise resolved (async)
scheduleMicroTask @ zone.js:585
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:236
Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:871
ZoneAwarePromise.then @ zone.js:981
PlatformRef
.bootstrapModuleWithZone @ application_ref.ts:333
PlatformRef
.bootstrapModule @ application_ref.ts:371
39 @ main.ts:11
webpack_require @ bootstrap 51c4dfb7eec49f792497:52
100 @ main.bundle.js:7
webpack_require @ bootstrap 51c4dfb7eec49f792497:52
webpackJsonpCallback @ bootstrap 51c4dfb7eec49f792497:23
(anonymous) @ main.bundle.js:1
errors.ts:42 ERROR Response {_body: "↵↵↵<meta char…n-cli/plugin-metadata.json↵↵↵", status: 404, ok: false, statusText: "Not Found", headers: Headers, …}
defaultErrorLogger @ errors.ts:42
ErrorHandler.handleError @ error_handler.ts:69
next @ application_ref.ts:371
schedulerFn @ event_emitter.ts:99
SafeSubscriber.tryOrUnsub @ Rx.js:983
SafeSubscriber.next @ Rx.js:930
Subscriber.next @ Rx.js:871
Subscriber.next @ Rx.js:835
Subject.next @ Rx.js:1463
EventEmitter.emit @ event_emitter.ts:80
(anonymous) @ ng_zone.ts:319
ZoneDelegate.invoke @ zone.js:392
Zone.run @ zone.js:142
NgZone.runOutsideAngular @ ng_zone.ts:247
onHandleError @ ng_zone.ts:319
ZoneDelegate.handleError @ zone.js:396
Zone.runTask @ zone.js:195
ZoneTask.invokeTask @ zone.js:499
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
XMLHttpRequest.send (async)
scheduleTask @ zone.js:2933
ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ long-stack-trace-zone.js:117
ZoneDelegate.scheduleTask @ zone.js:405
onScheduleTask @ zone.js:301
ZoneDelegate.scheduleTask @ zone.js:405
Zone.scheduleTask @ zone.js:236
Zone.scheduleMacroTask @ zone.js:259
(anonymous) @ zone.js:2966
proto.(anonymous function) @ zone.js:1366
(anonymous) @ xhr_backend.ts:156
Observable.trySubscribe @ Rx.js:1237
Observable.subscribe @ Rx.js:1225
MapOperator.call @ Rx.js:6167
Observable.subscribe @ Rx.js:1222
MapOperator.call @ Rx.js:6167
Observable.subscribe @ Rx.js:1222
webpackJsonp.43.DynamicComponentLoader.ngOnInit @ dynamic-plugin-loader.component.ts:51
checkAndUpdateDirectiveInline @ provider.ts:276
checkAndUpdateNodeInline @ view.ts:519
checkAndUpdateNode @ view.ts:462
debugCheckAndUpdateNode @ services.ts:389
debugCheckDirectivesFn @ services.ts:476
(anonymous) @ AppComponent.html:2
debugUpdateDirectives @ services.ts:455
checkAndUpdateView @ view.ts:375
callViewAction @ view.ts:770
execComponentViewsAction @ view.ts:703
checkAndUpdateView @ view.ts:432
callWithDebugContext @ services.ts:829
debugCheckAndUpdateView @ services.ts:397
ViewRef
.detectChanges @ refs.ts:441
(anonymous) @ application_ref.ts:713
ApplicationRef
.tick @ application_ref.ts:713
ApplicationRef
.loadComponent @ application_ref.ts:560
ApplicationRef
.bootstrap @ application_ref.ts:550
(anonymous) @ application_ref.ts:415
PlatformRef
.moduleDoBootstrap @ application_ref.ts:415
(anonymous) @ application_ref.ts:371
ZoneDelegate.invoke @ zone.js:392
onInvoke @ ng_zone.ts:296
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
(anonymous) @ zone.js:873
ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ ng_zone.ts:288
ZoneDelegate.invokeTask @ zone.js:424
Zone.runTask @ zone.js:192
drainMicroTaskQueue @ zone.js:602
Promise resolved (async)
scheduleMicroTask @ zone.js:585
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:236
Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:871
ZoneAwarePromise.then @ zone.js:981
PlatformRef
.bootstrapModuleWithZone @ application_ref.ts:333
PlatformRef
.bootstrapModule @ application_ref.ts:371
39 @ main.ts:11
webpack_require @ bootstrap 51c4dfb7eec49f792497:52
100 @ main.bundle.js:7
webpack_require @ bootstrap 51c4dfb7eec49f792497:52
webpackJsonpCallback @ bootstrap 51c4dfb7eec49f792497:23
(anonymous) @ main.bundle.js:1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.