angularangular-elementswebpack-externalsngx-build-plus

Sharing libraries among angular micro app elements


I have an micro app element and a shell app which works fine normally. However, I'm trying to build the micro app without the common libraries and refer to them from the global scope. I followed the following tutorial Building angular elements with sharing libraries

  1. ng g ngx-build-plus:externals
  2. npm run build:externals (ng serve --extra-webpack-config webpack.externals.js --output-hashing none --single-bundle)
  3. The file webpack.externals.js has the following externals defined

    module.exports = {
    "externals": {
        "rxjs": "rxjs",
        "@angular/core": "ng.core",
        "@angular/common": "ng.common",
        "@angular/common/http": "ng.common.http",
        "@angular/platform-browser": "ng.platformBrowser",
        "@angular/platform-browser-dynamic": "ng.platformBrowserDynamic",
        "@angular/compiler": "ng.compiler",
        "@angular/elements": "ng.elements",
    
        // Uncomment and add to scripts in angular.json if needed
        // "@angular/router": "ng.router",
        // "@angular/forms": "ng.forms"
       }
    }
    
  4. In the angular.json te following scripts are there

"scripts": [
              "node_modules/rxjs/bundles/rxjs.umd.js",
              "node_modules/@angular/core/bundles/core.umd.js",
              "node_modules/@angular/common/bundles/common.umd.js",
              "node_modules/@angular/common/bundles/common-http.umd.js",
              "node_modules/@angular/compiler/bundles/compiler.umd.js",
              "node_modules/@angular/elements/bundles/elements.umd.js",
              "node_modules/@angular/platform-browser/bundles/platform-browser.umd.js",
              "node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"
            ]

But now, the element is not loading in the shell app. It says "Uncaught ReferenceError: ng is not defined at Object.@angular/core". I'm very new to angular, ave I missed a step here? It looks like the angular.json scripts are not working and element (micro app) is unable to refer to the global array


Solution

  • I had same issue as yours, I am trying to embed an angular element into an angular app with ng-build-plus, this is how I resolved it:

    1. double check tag order, place script.js before main.js (so angular get loaded first)
    2. add below two scripts above script.js
    <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.2.10/custom-elements-es5-adapter.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/zone.js/0.9.1/zone.min.js"></script>