DEV Community

Andre Sander
Andre Sander

Posted on

Using sass/scss inside lit elements

Recently, I was trying to use sass for my lit elements. Neither StackOverflow nor my LLM turned out to be helpful, but ultimately I figured it out! Here's a quick run down on what needs to be done.

For the record, I bootstrapped my project using npm create vite@latest my-library -- --template lit-ts and am version 3.3.0 of lit.

Install sass

Vite supports CSS preprocessors, but we need to make sure that they are installed.

npm i -D sass # I'm using sass@1.93.2 but this might also work for newer versions
Enter fullscreen mode Exit fullscreen mode

Configuration in vite.config.ts (optional)

In my case, I wanted to provide some sass variables globally so that I could use them in my lit element styles.

import { resolve } from "path";
import { defineConfig } from "vite";

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `
          @use "${resolve(__dirname, "./scss/variables")}";
        `,
      },
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Adding component styles

/* file: /my-thing/styles.scss */
:host {
  display: block;
  color: #{variables.$primary};
}
Enter fullscreen mode Exit fullscreen mode

Integrating the styles

// file: /my-thing/element.ts
import { LitElement, html, unsafeCSS } from "lit";
import styles from './styles.scss?inline';

export class MyThing extends LitElement {
  static styles = unsafeCSS(styles)

  render() {
    return html`
      <div>Hello World!</div>
    `;
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Vite already has all it takes to preprocess sass. No additional plugins are necessary to achieve integrating sass styles into lit elements.

One crucial point is importing styles using ?inline, which means importing without automatic injection of CSS contents.

Having to use unsafeCSS() is not pretty, but I don't consider it to be a security issue, because I am in control of the contents of the injected and processed styles.

Hope this helps!

Top comments (0)