I am trying to configure webpack to insert my custom SCSS styles into a shadow DOM node instead of at the head of the document. The location of the shadow DOM node will not always be consistent, so the ability to pass an element to insert the styles into dynamically is key.
The documentation references a function that can be used in style-loader configuration called insert that allows a function to be created in order to specify where the styles are to be added. Importing the styles and calling the use function with a target parameter is how the example specifies the other element for the styles to be added to.
The issue I am having is the second parameter called options in the insert function is always undefined. The element argument is present and contains the correct custom styles tag contents, but the options object that specifies where to add these styles to is never defined so the styles end up getting added to the document head which is not the desired outcome.
Here is my relevant webpack code:
module: {
rules: [
{
test: /\.css$/i,
exclude: /\.lazy\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.scss$/,
exclude: /\.lazy\.scss$/i,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.lazy\.scss$/i,
use: [
{
loader: 'style-loader',
options: {
injectType: 'lazyStyleTag',
insert: function insertIntoTarget(element, options) {
var parent = null;
if (!options) {
parent = document.head;
} else {
parent = options.target;
}
parent.appendChild(element);
},
},
},
'css-loader',
'sass-loader',
],
},
]
}
Here is the relevant react code:
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './styles/Component.lazy.scss';
const Component = () => {
return (
<div>Component in shadow DOM</div>
);
};
if (document.querySelector('div.ComponentClass') === null) {
const container = document.createElement('div');
container.className = 'ComponentClass';
document.body.appendChild(container);
const shadow = document.querySelector('div.ComponentClass').attachShadow({ mode: 'open' });
const target = document.querySelector('div.ComponentClass').shadowRoot;
styles.use({ target });
ReactDOM.render(<Component />, target);
}
Is there anything I am doing wrong here that is causing the options parameter to always be undefined?
I have also tried a few variations of passing different things into the styles.use functions as well, such as { options: { target: ... } } and it seems that only the element parameter is passed in no matter what