How to create and style svelte 3 custom elements with nested components?

This is because when customElement option is on, each style in a component is injected into the shadowRoot of the custom element.

class YourComponent extends SvelteElement {
        constructor(options) {
            super();

            this.shadowRoot.innerHTML = `<style>.foo{color:red;}</style>`;
// continues

Thus, in order to make style appear, you must use svelte component as custom element, not as svelte component.

Your App.svelte should be like below.

<script>
    import Foo from './Foo.svelte'
    import Bar from './Bar.svelte'
</script>
<svelte:options tag="web-component" />

<foo-component/>
<bar-component/>

However, this neither solve the problems related with custom element.

  1. :global selector is not transformed into actual global selector.

  2. Every nested component will produce shadowRoot, whereas mostly you will want only top-level one.

Check out some issues below from svelte repository related to custom elements.

  • nested component in custom element does not inherit style #2605
  • :global(...) not working in custom elements #2969

It seems like svelte does not fully support style cascading in custom element yet, should be handled in future.

Checked in svelte v3.12.1.