I am working on a personal ReactJS project and have created two projects using Module Federation.
In the main project, I added some CSS which is affecting the remote project. After Googling, I found that a better way to handle this is by using Shadow DOM, which isolates the remote component.
However, while implementing the Shadow DOM, I'm unable to inject or apply SCSS styles to the elements.
I am using Create React App with CRACO, and I have included the craco.config.js file below.
Does anyone have any ideas on how to inject SCSS?
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './components/App';
import './index.scss';
// Get the root container
const container = document.getElementById('root') as HTMLElement;
// Create the Shadow Root
const shadowRoot = container.attachShadow({ mode: 'open' });
// Create an app container inside Shadow DOM
const shadowAppContainer = document.createElement('div');
shadowRoot.appendChild(shadowAppContainer);
// Mount React into the shadow root
const root = ReactDOM.createRoot(shadowAppContainer);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Craco.config.js:
module.exports = function () {
const env = process.env.ENV || 'local';
return {
plugins: [
{
plugin: require('./build/craco'),
},
],
style: {
sass: {
loaderOptions: {
// Prefer 'sass' (dart-sass) over 'node-sass' if both packages are installed.
implementation: require('sass'),
// Workaround for this bug: https://github.com/webpack-contrib/sass-loader/issues/804
webpackImporter: false,
},
},
},
webpack: {
plugins: {
remove: ['ModuleScopePlugin'],
},
},
};
};
Peter B
24.7k5 gold badges42 silver badges94 bronze badges
lang-js
import "style.scss"imports, but what exactly would that do? Append the style to the page? There is no object you load here, so there is no way to make it apply to theShadowRootfrom this point. Now if the imported object is<style>tag you could append it, or if it's aCSSStyleSheetyou could adopt it in yourShadowRoot. But from this it seems the style might just be part of thedocument, which would not cascade into yourShadowRoot.import Style from "style.css" with { type: "stylesheet" }then the browser usually returns aCSSStyleSheetwhich you can adopt in yourshadowRootwith.shadowRoot.adoptedStyleSheets = [ Style ]. But I'm not all to familiar with how all the webpack/rollup/react stuff handles this...