在 angular 个微应用元素之间共享库

Sharing libraries among angular micro app elements

我有一个微型应用程序元素和一个 shell 应用程序,可以正常运行。但是,我正在尝试构建没有公共库的微型应用程序,并从全球范围内引用它们。我遵循了以下教程 Building angular elements with sharing libraries

  1. ng g ngx-build-plus:外部
  2. npm 运行 build:externals (ng serve --extra-webpack-config webpack.externals.js --output-hashing none --single-bundle)
  3. 文件 webpack.externals.js 定义了以下外部变量

    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. 在 angular.json 中有以下脚本

"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"
            ]

但是现在,该元素未加载到 shell 应用程序中。它说 “Uncaught ReferenceError: ng 未定义在 Object.@angular/core”。 我是 angular 的新手,我错过了这里的一步吗? angular.json 脚本似乎无法正常工作,元素(微应用)无法引用全局数组

我遇到了和你一样的问题,我正在尝试将 angular 元素嵌入到带有 ng-build-plus 的 angular 应用程序中,我是这样解决的:

  1. 仔细检查标签顺序,将 script.js 放在 main.js 之前(因此 angular 首先加载)
  2. 在上面添加下面两个脚本 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>

我遇到了同样的错误,但是 ExploreEv 的 2 个脚本不知何故没有解决它。在 Manfred Steyer 的帮助下,它终于成功了:

https://github.com/manfredsteyer/ngx-build-plus/issues/5

  1. 运行 npm i @webcomponents/custom-elements --save
  2. 导入此脚本:"scripts": [ "node_modules/@webcomponents/custom-elements/src/native-shim.js" ]
  3. 确保在 main.js
  4. 之前导入 polyfills 和 scripts.js