title: Load new modules dynamically in run-time with Angular CLI & Angular 5
body: <p>Currently I'm working on a project which is being hosted on a clients server. For new 'modules' there is <strong>no intention to recompile</strong> the entire application. That said, the client wants to <strong>update the router/lazy loaded modules in runtime</strong>. I've tried several things out but I can't get it to work. I was wondering if any of you knows what I could still try or what I missed.</p>
  
  <p>One thing I noticed, most of the resources I tried, using angular cli, are being bundled into seperate chunks by webpack by default when building the application. Which seems logical as it makes use of the webpack code splitting. but what if the module is not known yet at compile time (but a compiled module is stored somewhere on a server)? The bundling does not work because it can't find the module to import. And Using SystemJS will load up UMD modules whenever found on the system, but are also bundled in a seperate chunk by webpack.</p>
  
  <p>Some resources I already tried;</p>
  
  <ul>
  <li><a href="https://github.com/dianadujing/dynamic-remote-component-loader" rel="noreferrer">dynamic-remote-component-loader</a></li>
  <li><a href="https://github.com/Toxicable/module-loading" rel="noreferrer">module-loading</a></li>
  <li><a href="https://stackoverflow.com/questions/42953858/loading-modules-from-different-server-at-runtime">Loading modules from different server at runtime</a></li>
  <li><a href="https://stackoverflow.com/questions/45503497/how-to-load-dynamic-external-components-into-angular-application">How to load dynamic external components into Angular application</a></li>
  <li><a href="https://stackoverflow.com/questions/41438198/implementing-a-plugin-architecture-plugin-system-pluggable-framework-in-angu">Implementing a plugin architecture / plugin system / pluggable framework in Angular 2, 4, 5, 6</a></li>
  <li><a href="https://stackoverflow.com/questions/48590455/angular-5-load-modules-that-are-not-known-at-compile-time-dynamically-at-run">Angular 5 - load modules (that are not known at compile time) dynamically at run-time</a></li>
  <li><a href="https://medium.com/@nikolasleblanc/building-an-angular-4-component-library-with-the-angular-cli-and-ng-packagr-53b2ade0701e" rel="noreferrer">https://medium.com/@nikolasleblanc/building-an-angular-4-component-library-with-the-angular-cli-and-ng-packagr-53b2ade0701e</a></li>
  <li>Some several other relating this topic.</li>
  </ul>
  
  <p>Some code I already tried and implement, but not working at this time;</p>
  
  <p>Extending router with normal module.ts file</p>
  
  <pre><code>  this.router.config.push({
      path: "external",
      loadChildren: () =&gt;
        System.import("./module/external.module").then(
          module =&gt; module["ExternalModule"],
          () =&gt; {
            throw { loadChunkError: true };
          }
        )
    });
  </code></pre>
  
  <p>Normal SystemJS Import of UMD bundle</p>
  
  <pre><code>System.import("./external/bundles/external.umd.js").then(modules =&gt; {
    console.log(modules);
    this.compiler.compileModuleAndAllComponentsAsync(modules['External'])
      .then(compiled =&gt; {
        const m = compiled.ngModuleFactory.create(this.injector);
        const factory = compiled.componentFactories[0];
        const cmp = factory.create(this.injector, [], null, m);
      });
  });
  </code></pre>
  
  <p>Import external module, not working with webpack (afaik)</p>
  
  <pre><code>const url = 'https://gist.githubusercontent.com/dianadujing/a7bbbf191349182e1d459286dba0282f/raw/c23281f8c5fabb10ab9d144489316919e4233d11/app.module.ts';
  const importer = (url:any) =&gt; Observable.fromPromise(System.import(url));
  console.log('importer:', importer);
  importer(url)
    .subscribe((modules) =&gt; {
      console.log('modules:', modules, modules['AppModule']);
      this.cfr = this.compiler
        .compileModuleAndAllComponentsSync(modules['AppModule']);
      console.log(this.cfr,',', this.cfr.componentFactories[0]);
      this.external.createComponent(this.cfr.componentFactories[0], 0);
  });
  </code></pre>
  
  <p>Use SystemJsNgModuleLoader</p>
  
  <pre><code>this.loader.load('app/lazy/lazy.module#LazyModule')
    .then((moduleFactory: NgModuleFactory&lt;any&gt;) =&gt; {
      console.log(moduleFactory);
      const entryComponent = (&lt;any&gt;moduleFactory.moduleType).entry;
      const moduleRef = moduleFactory.create(this.injector);
  
      const compFactory = moduleRef.componentFactoryResolver
        .resolveComponentFactory(entryComponent);
    });
  </code></pre>
  
  <p>Tried loading a module made with rollup</p>
  
  <pre><code>this.http.get(`./myplugin/${metadataFileName}`)
    .map(res =&gt; res.json())
    .map((metadata: PluginMetadata) =&gt; {
  
      // create the element to load in the module and factories
      const script = document.createElement('script');
      script.src = `./myplugin/${factoryFileName}`;
  
      script.onload = () =&gt; {
        //rollup builds the bundle so it's attached to the window 
        //object when loaded in
        const moduleFactory: NgModuleFactory&lt;any&gt; = 
          window[metadata.name][metadata.moduleName + factorySuffix];
        const moduleRef = moduleFactory.create(this.injector);
  
        //use the entry point token to grab the component type that 
        //we should be rendering
        const compType = moduleRef.injector.get(pluginEntryPointToken);
        const compFactory = moduleRef.componentFactoryResolver
          .resolveComponentFactory(compType); 
  // Works perfectly in debug, but when building for production it
  // returns an error 'cannot find name Component of undefined' 
  // Not getting it to work with the router module.
      }
  
      document.head.appendChild(script);
  
    }).subscribe();
  </code></pre>
  
  <p>Example with SystemJsNgModuleLoader only works when the Module is already provided as 'lazy' route in the RouterModule of the app (which turns it into a chunk when built with webpack)</p>
  
  <p>I found a lot of discussion about this topic on StackOverflow here and there and provided solutions seem really good of loading modules/components dynamically if known up front. but none is fitting for our use case of the project. Please let me know what I can still try or dive into.</p>
  
  <p>Thanks!</p>
  
  <p>EDIT: I've found; <a href="https://github.com/kirjs/angular-dynamic-module-loading" rel="noreferrer">https://github.com/kirjs/angular-dynamic-module-loading</a> and will give this a try.</p>
  
  <p>UPDATE: I've created a repository with an example of loading modules dynamically using SystemJS (and using Angular 6); <a href="https://github.com/lmeijdam/angular-umd-dynamic-example" rel="noreferrer">https://github.com/lmeijdam/angular-umd-dynamic-example</a></p>