Multiple Angular Elements from different scripts

跟風遠走 提交于 2019-12-02 00:47:05

The feature to have multiple angular micro apps on the same page is currently not supported.

The error that you see actually describes the issue well. When you load your second micro app, bootstrap will run and try to bootstrap the module by calling it's ngDoBootstrap method. If you do some detailed logging though, you will notice that it tries to invoke ngDoBootstrap on the first micro app for the second time. If you want to make this work, you would need to do some manual work to control the bootstrap process yourself and make sure to bootstrap the correct module when it is introduced on the page.

Resource

The building of the distribution assets webpack assigns by default the window.webpackJsonp variable, however with multiple Elements wrapped up that way you will when it parses the bundle this variable is already assigned and runs with the existing code.

You can monkey patch that by giving this variable in your bundle process a more unique name. I just added the Element name to the name of the webpackJsonp, which solved this issue.

Just to update this so other users will find a solution. This is now possible using the Angular Custom Webpack Builder.

In angular.json

      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./apps/custom-elements/extra-webpack.config.js",
              "mergeStrategies": { "externals": "replace" }
            },
            ...

And in the extra-webpack.config.js file add something like this:

module.exports = {
  output: {
    jsonpFunction: 'webpackJsonpElements',
    library: 'elements',
  },
}

If it still doesn't work have a go at adding/removing the polyfills from the Polyfills.ts file and adding/removing the custom-elements-es5-adapter.js which you can pull from here

Use a unique tag name to define your Angular Element. That should prevent this issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!