javascriptweb-componentpackage.jsonlit-elementunpkg

Web Component not rendering when loaded from UNPKG CDN?


I'm trying to render a web component in Stackblitz using the UNPKG CDN.

This is the script element that should load it:

<script src="https://unpkg.com/fspubtest1234"></script>

And with that in the head element we should get the hello-world custom component to render.

    <h1>UNPKG CDN TEST</h1>
    <hello-world name="Doffen"></hello-world>

However it does not. If we paste the URL (https://unpkg.com/fspubtest1234) used in the script tag directly into the browser address bar we get the bundle:

class t extends HTMLElement{static get observedAttributes(){return["name"]}constructor(){super(),this.name="World"}connectedCallback(){this.textContent=`Hello ${this.name}!`}attributeChangedCallback(t,e,r){if(e!==r){if("name"!==t)throw new Error(`Unhandled attribute: ${t}`);this.name=r}}}customElements.define("hello-world",t);class e{constructor(){this.name="Ole"}}export{t as HelloWorldComponent,e as Person};

And if we paste that script into the Stackblitz script.js file, the custom element renders.

Any ideas on how to get it to work with the UNPKG CDN?


Solution

  • The script needs type="module".

    This is the fixed version.

    <script type="module" src="https://unpkg.com/fspubtest1234"></script>
    
    

    Otherwise it fails with the error

    SyntaxError: Unexpected token 'export'
    

    The web component module script is generated from the latest lit element rollup configuration, and it has the output set as esm, and so it will include the export keyword.

    Previous versions of lit element had the output set as iife, and so the type="module" property was not required in order to get the script to run.