ant-design / cssinjs

https://ant-design.github.io/cssinjs
MIT License
237 stars 59 forks source link

Support for Web Components #28

Closed felixschorer closed 1 year ago

felixschorer commented 2 years ago

Hello,

will there be an option to customize where the styles will be injected at runtime by the CSS-in-JS implementation?

We are currently using Antd v4 within Web Components to author micro frontends. Each micro frontend is a separate Web Component which internally uses a number of Antd components. We're using shadow DOM to isolate the styles of the different micro frontends.

I briefly looked through the code in this repository. If I understood the code correctly, the styles will currently be injected into the head of the document? This would break our approach to micro frontends as the Antd styles wouldn't be able to penetrate into the shadow DOM of our Web Components.

From my very basic understanding, it may be simple to add that feature. However, I am unaware of any constraints related to SSR.

The updateCSS function from rc-util already provides a way to override the HTML element where the styles will be injected using the attachTo option. Also, the StyleProvider already checks whether there is a parent StyleContext present. By providing a parent StyleContext in the application code it could be possible to implement a mechanism to override the HTML element where the styles will be injected:

  export interface StyleContextProps {
    autoClear?: boolean;
    mock?: 'server' | 'client';
    cache: CacheEntity;
    defaultCache: boolean;
+   attachTo: Element;
  }

Since Antd v4 isn't compatible with React 18, we will have to upgrade Antd v5 eventually. We would greatly appreciate it if there could be a solution to this problem.

Kind regards, Felix Schorer

zombieJ commented 2 years ago

Thanks for feedback. Since current lib is alpha version. We may make sure it works as expect for basic requirement. But yes, this function seems helpful which should be added in.

felixschorer commented 1 year ago

I was able to make it work by nesting the app inside a StyleProvider:

import { StyleProvider } from '@ant-design/cssinjs'

<StyleProvider container={someElement}>
  <App />
</StyleProvider>

Thank you so much for making this work.