@vanilla-extract/css - is there a way to export stylesheet CSS for shadow DOM

545 Views Asked by At

I am looking at @vanilla-extract/css for my styling in React app. The method style exports a className from the *.css.ts file but I require inline styling for Shadow DOM encapsulation.

I was checking @stitches/react it provides a way called createCss were a css is a named export of the method.

I don't see any similar methods in @vanilla-extract/css.

export const sprinkles = createSprinkles(
  responsiveProperties,
  colorProperties
);

export const appStyle = sprinkles({
  display: 'flex',
  paddingTop: 'small',
  backgroundColor: 'red'
});

console.log(appStyle) // => gives obfuscated css classname `_1jbh1078`


UPDATE 1

Though the question remains valid, but I have moved forward with @stitches/react at this point. See my answer for @stitches/react way of doing things.

1

There are 1 best solutions below

0
On

Looks like @vanilla-extract/css doesn't give a way to export CSS. But @stitches/css has done a good job with some caveats.

import * as React from 'react';
import ReactDOM from 'react-dom/client';
import { createStitches } from '@stitches/react';

const { styled, getCssText, css } = createStitches({
  theme: {
    colors: {
      red: '#F00',
      blue: 'blue'
    }
  }
});

const box = css({
  background: '$red',
  color: '$blue'
});

const element: HTMLElement = document.getElementById('root');

const shadowRoot = ReactDOM.createRoot(
  element.attachShadow({ mode: 'open' })
);

shadowRoot.render(<><div className={box()}>App Colored</div><style>{getCssText()}</style></>);
  1. The getCssText extracts all the style sheets from the config and puts it under <style /> tags - The issue here is stitches/react has no ways to tree shaking unwanted variables.
  2. The <style> tag in the Shadow DOM should only be placed after all the css functions are consumed.