Extract CSS from Lit tagged templates

56 Views Asked by At

We are in a situation where we have to ship some of the global styles written with Lit tagged templates as plain css files.

Basically converting the following:

// global.ts
import { css, unsafeCSS } from 'lit';
import * as tokens from 'xyz-design-tokens';

export default css`
  h1 {
    font-size: ${unsafeCSS(tokens.h1FontSize)};
  }
`;

to

/* global.css */
h1 {
  font-size: 3rem;
}

I'v tried to use postcss-cli and postcss-lit but it just ends up outputting the same content of the global.ts file. Is there any way to extract CSS out of the tagged templates and output as css files?

1

There are 1 best solutions below

2
W.K.C On BEST ANSWER

For the "output" part, you might have to use the fs module to process your lit files in batch.

To extract (the computed) CSS out of the tagged templates, you can access cssText.

const tokens = {
  h1Color: "red"
}
const style = css`
  h1 {
    font-size: "16px";
    color: ${unsafeCSS(tokens.h1Color)};
  }
`;
console.log(style.cssText); 

enter image description here

For css inside a lit class, you need to create an object from the class. Then you access the it as a property.

@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
  themeCss = `
    h1 {
      color: ${unsafeCSS(tokens.h1Color)};
    }
  `;
  
  render() {
    
    return html`
        <div>
          <style>${this.themeCss}</style>
          <h1>Hello world</h1>
        </div>
    `;
  }
}
const greet = new SimpleGreeting()
console.log(greet.themeCss);

enter image description here

See this lit playground demo in action