I am writing a library with which you can render a React application as a web component. Like so:
ReactWebComponent.create(<App />, 'my-react-web-component', { css: 'inject' });
You can see there is an option { css: 'inject' }
. To create a web component with CSS I need to add <link>
tags to the shadow dom. This happens inside my library.
Dummy Code:
ReactWebComponent.create = function(options) {
const proto = Object.create(HTMLElement.prototype, {
attachedCallback: {
value: function() {
const mountPoint = document.createElement('span');
const shadowRoot = this.createShadowRoot();
shadowRoot.appendChild(mountPoint);
shadowRoot.insertAdjacentHTML('beforeend', options.css);
ReactDOM.render(<App />, mountPoint);
}
}
});
document.registerElement('react-web-component', {prototype: proto});
};
Now of course I do not want to append the string 'inject'
. Instead I want to write a Webpack plugin
or loader
that takes the CSS files generated by extract-text-webpack-plugin and injects the corresponding <link>
tags where there is 'inject'
. So from
ReactWebComponent.create(<App />, 'my-react-web-component', { css: 'inject' });
I want to generate this
ReactWebComponent.create(<App />, 'my-react-web-component', { css: '<link rel="stylesheet" type="text/css" href="styles.a4e5f9.css">' });
I think the replacement part can easily be done with RegEx
, but I am troubled with how to get the CSS file name and how to transform the JS file.