DEV Community

SHAREEJ V K
SHAREEJ V K

Posted on • Edited on

Experiment With Svelte to load external /un-scoped css in custom elements and also to support css variable syntax

How to load external/ global css in svelte custom components and how to get support for css variable syntax ... This was one of the challenge I faced when I got started with svelte. I was coming from the Angular world and things were not easy .. I had tried many ways to achieve this but nothing helped until I did a small experiment.

As the style get appended in to the shadow root, svelte global selector was not working with custom elements as expected. I tried with many rollup css plugins, but none of them worked for custom elements. The only way to achieve this was to bypass svelte and append the style dynamically inside the shadow root once the custom component got registered with in the DOM. It was really a hacky way of doing it but there were no other ways I could think about.

This is what I did :)

Alt Text

It was totally an experiment but surprisingly the style got appended and executed in the shadow root without getting trimmed or scoped.

Alt Text

So the first issue solved !!!!
but what about the variable syntax "var(--variable )" support ??

It was still not working .. :(

until I did this

Alt Text

Now everything worked as expected.

TL;DR ::: if you really have a requirement like this just load the external global css inside the custom component using the svelte Element bind (bind/this) API. and load the global variables css using the svelte:head API

Hope we will have a proper way of doing it in svelte soon.

Top comments (0)