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
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")}";
`,
},
},
},
});
Adding component styles
/* file: /my-thing/styles.scss */
:host {
display: block;
color: #{variables.$primary};
}
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>
`;
}
}
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)