2

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 Answer 1

0

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

2
  • I dont think this addresses the concern of the OP.
    – puter
    Commented Jan 23 at 19:05
  • My bad.. read the question wrongly. I've updated the answer
    – W.K.C
    Commented Jan 27 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.