CSS-in-JS with Aurelia

Hi,
We encountered a lot of obstacles in the current version of Aurelia-Toolbelt that we are trying to fix for the next version.
One of the problems is the use of variables for CSS files (such as color, height, width, font, … for different config and size).

In our current version, we use DOM.injectStyles, along with a unique string identifier. (usually component_name + _injected_style )

injectStyles(styles: string, destination?: Element, prepend?: boolean, id?: string): Node

like

let css = `.is-divider-vertical[data-content]::after,.is-divider[data-content]::after{
      background:${this.backgroundColor}!important;color:${this.color}!important}
      .is-divider{border-top:.1rem solid ${this.lineColor}!important;}
      .is-divider-vertical::before{border-left:.1rem solid ${this.lineColor}!important;}
      `;
DOM.injectStyles(css, null, null, 'aut_divider_injected_style');

I am looking for a better and cleaner way.
I wanted to know if we use CSS-in-JS like emotion, Is good for this purpose?
What are its strengths and weaknesses?
How do you manage these terms in general? (Especially when you convert a third-party library with existing styles)

Thanks.

2 Likes

Forgive me if this is not relevant but have you checked modifying stylesheet rules with CSSOM?

<script type="text/javascript">
var stylesheet = document.styleSheets[1];
stylesheet.cssRules[0].style.backgroundColor="blue";
</script>
1 Like

@constructor, I think your way is very similar to the current situation. You find a style first and then change it.

Please consider the following links:

injectStyles() with optional Id
injectStyles source

an identifier to replace the previous style if needed.

We work with a unique string id for each style and we can update it again and again. (a whole style of course, not a variable!)

Why do you think this way is better than working with a CSS string as a JS module?

1 Like

My initial thought was triggered by seeing CSS as a string. I thought that storing styles in CSS files seemed simpler to manage.

let css = cssStore.getStyles(this);
DOM.injectStyles(css, null, null, 'aut_divider_injected_style');

Here, the cssStore would be a service responsible for retrieving the CSS from a file and applying any transformations.

Without understanding your use case more I could not answer fully, this was just my initial impression based upon reading your post and may not be correct or appropriate.

2 Likes

I wrote a Medium post CSS-in-JS in Aurelia 2

3 Likes