react-shadow-root
react-shadow-root copied to clipboard
Loading scss files instead of using inline style
Is it possible to load css/scss files in the shadow root? Which configuration is needed in webpack?
This is something I have long been meaning to look into. I still have not figured out the webpack config but you can do it in your component file. I am using create react app so I made sure to install node-sass. You will also need the webpack raw-loader package. Then you can say import myStyles from '!!raw-loader!sass-loader!./my-styles.scss';
Create react app will complain about this so you have to add /* eslint import/no-webpack-loader-syntax: off */
above the import line.
Then you can say
import myStyles from '!!raw-loader!sass-loader!./my-styles.scss';
how to load the css file using the <link>
tag instead of getting the content of the css during the production build? the above line import the content of the css
@noskcire11 Just put the link
tag in the shadow root and it will load and scope the styles.
in production build using create react app will separate the css files from the html. any idea how to do that in the shadow root?
This is what I use: https://github.com/pixiebrix/pixiebrix-extension/blob/c1b475f51de089a3d8734793e892463283ba251b/src/components/quickBar/QuickBarApp.tsx
import faStyleSheet from "@fortawesome/fontawesome-svg-core/styles.css?loadAsUrl";
<ReactShadowRoot mode="closed">
<link rel="stylesheet" href={faStyleSheet} />
</ReactShadowRoot>
And this is the webpack configuration to enable that loadAsUrl
query: https://github.com/pixiebrix/pixiebrix-extension/blob/c1b475f51de089a3d8734793e892463283ba251b/webpack.sharedConfig.js#L102-L108
module.exports = {
module: {
rules: [
{
resourceQuery: /loadAsUrl/,
type: "asset/resource",
generator: {
filename: "css/[name][ext]" // The file will be generated here
}
}
]
}
}
One problem I have though is FOUC, because the shadow-dom content is appended together with the stylesheet so it renders before the sheet is parsed. I documented it here, but I don't have a solution for it yet, help welcome:
- https://github.com/pixiebrix/pixiebrix-extension/issues/2299
Edit: Found a solution!
https://github.com/pixiebrix/pixiebrix-extension/blob/9271edae68c69bb2a6539a7f8add15fb4947b4f0/src/components/quickBar/QuickBarApp.tsx#L288-L289 https://github.com/pixiebrix/pixiebrix-extension/blob/9271edae68c69bb2a6539a7f8add15fb4947b4f0/src/components/Stylesheet.tsx
for anyone using cra:
import url from "!!file-loader?name=static/css/[contenthash].css!sass-loader!./style.scss"
<ReactShadowRoot>
<link rel="stylesheet" href={url} />
</ReactShadowRoot>
I also need it