Search code examples
web-componentstenciljsastrojs

Import StencilJs generated web-component in Astro


I have build a web-component with StencilJs and published it to NPM and would like to use it in an Astro project.

However the web-component does not load.

package.json:

"obfuscate-link-web-component": "^0.0.2",

In the astro page i use a script tag to import the webcomponent

<Layout title="Impressum" description="Impressum">
      E-Mail: <obfuscate-link email="aGV..."></obfuscate-link><br />
</Layout>
<script>
import('obfuscate-link-web-component');
</script>

I can see that the index.js for type module loads from the package.json of the web-component loads but it is not executed.

I suppose it has something to do with the lazy-loading of Stencil.
How can i load the web-component?

Note that i can not use full qualified path to aspecific file in node_modules since this will not work when Astro builds the site.


Update I changed the component outputTargets to dist-custom-elements as suggested and www and changed the package.json entrypoints to "main": "dist/components/index.js"

Now i can use it like this:

<script>
import { ObfuscateLink } from 'obfuscate-link-web-component';
customElements.define('obfuscate-link', ObfuscateLink);
</script>

Or

<script src="https://unpkg.com/[email protected]/dist/components/obfuscate-link.js"></script>

Solution

  • I don't know about Astro, but a Stencil component/library is not a single file "index.js" it is a kind of "loader" file e.g. "/dist/obfuscate-link-web-component/obfuscate-link-web-component.esm.js" that dynamically loads other files.

    You might want to look into the custom elements build option (https://stenciljs.com/docs/custom-elements) which is useful when dynamic loading is not desired.

    It might also be possible to change the module or main package.json property to point to the esm.js loader instead of index - I have no idea if this will work or not.