首页 > 解决方案 > How to build simple polymer webcomponent so it's reusable?

问题描述

So, I want to include several unrelated webcomponents in one html page and we are trying to do so with Polymer.

Each webcomponent on it's own is working fine but combining multiple of them is causing a lot of headache.

What did I do to show the problem:

I now want to build and bundle them (since my components have some dependencies) into 1 js file... and this is where I'm stuck. I tried with the following polymer.json:

{
  "entrypoint": "index.html",
  "shell": "test-element.js",
  "npm": true,
  "lint": {
    "rules": [
      "polymer-3"
    ]
  },
  "builds": [
      { 
        "name": "es6prod",
        "preset": "es6-bundled",
        "addServiceWorker": false,
        "bundle": {
          "inlineCss": true,          
          "inlineScripts": false,      
          "rewriteUrlsInTemplates": true, 
          "sourcemaps": true,     
          "stripComments": true
        }
      }
      ]
}

So, now I created a simple webpage where I'd like to include them:

<html>
    <head><script>/*a whole lot of javascript so the define function is available*/</script>
    </head>
    <body>
        <h1>Testing multiple polymer components</h1>

        <test-element-a></test-element-a>
        <test-element-b></test-element-b>

        <script type="module" src="./polymer-element-a/build/es6prod/test-element.js"></script>
        <script type="module" src="./polymer-element-b/build/es6prod/test-element.js"></script>
    </body>
</html>

And here I have the problem that only the first webcomponent loads... for the second, an error is available in the console:

(index):2 Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry
    at http://127.0.0.1:8081/polymer-element-b/build/es6prod/test-element.js:1:4222
    at f (http://127.0.0.1:8081/:2:10783)
    at http://127.0.0.1:8081/:2:10676
    at h (http://127.0.0.1:8081/:2:11004)
    at e (http://127.0.0.1:8081/:2:10639)
    at http://127.0.0.1:8081/:2:12620
    at j (http://127.0.0.1:8081/:2:11604)
    at http://127.0.0.1:8081/:2:12602

If I dig deeper, this is because the following happens twice: customElements.define("dom-module",DomModule), once for every component.

So, my question: how to build polymer webcomponents so that we can make them reusable?

标签: javascriptpolymerweb-component

解决方案


推荐阅读