SCSS external Link to styling component in LitElement

Viewed 1098

The purpose of the web components is to encapsulate all HTML/CSS/JS in one place, but I must use general SCSS files, that have a lot of variables such as color, font size and a lot of other stuff. It's a design system and it's always changing. Is there a plugin or a way to solve this problem?

1 Answers

If the purpose of those Sass files is to only expose some variables then probably the smartest thing to do is converting them to CSS custom properties: they're the recommended and most effective way to theme WebComponents.

@use 'sass:meta';
@use 'variables-file-1'; // Import the variable files
@use 'variables-file-2'; // as Sass modules
// ...

@mixin export-vars($module-name) {
  // Use module-variables() to extract a name-to-value map of the
  // variables declared in the module identified by $module-name
  @each $name, $value in meta.module-variables($module-name) {
    --#{$name}: #{$value}; // Define an equivalent CSS custom prop
  }
}


:root {
  @include export-vars(variables-file-1);
  @include export-vars(variables-file-2);
  // ...
}

You can then import the compiled CSS (a normal <link> in index.html is fine in most cases since CSS custom properties cross shadow DOM boundaries) and use the variables in your components:

import { LitElement, html, css, customElement } from 'lit-element';

@customElement('my-component')
export class MyComponent extends LitElement {

  static styles = css`
    :host {
      color: var(--my-var, <fallback-value>);
    }
  `;

}

With this said, if you need to share styles between LitElements, that is possible as well.

Related