Here are the steps to create a module utilizing esbuild and the esbuild-css-modules-plugin to append css to body.shadowRoot:
Install the required modules:
npm install esbuild esbuild-css-modules-plugin --save-dev
Create a JavaScript file where you will define your module logic:
import esbuild from 'esbuild';
import cssModulesPlugin from 'esbuild-css-modules-plugin';
// Define your module code
const appendCssToShadowRoot = async (css, options = {}) => {
// Create a stylesheet and add the css rules as content
const styleSheet = new CSSStyleSheet();
await styleSheet.replace(css);
// Get the body element and its shadow root
const body = document.querySelector('body');
const shadowRoot = body.shadowRoot || body.attachShadow({ mode: 'open' });
// Append the stylesheet to the shadow root
const styleElement = document.createElement('style');
styleElement.id = options.id;
styleElement.appendChild(styleSheet.cssRules[0].cssText);
shadowRoot.appendChild(styleElement);
}
// Export your module function
export default appendCssToShadowRoot;
Compile the module file using esbuild and the esbuild-css-modules-plugin:
esbuild.build({
entryPoints: ['path/to/your/module.js'],
bundle: true,
outfile: 'dist/module.js',
plugins: [
cssModulesPlugin({
inject: false,
generateScopedName: '[local]__[hash:base64:8]',
}),
],
});
Include the compiled module file in your HTML file:
<script src="path/to/your/dist/module.js"></script>
You can now use the appendCssToShadowRoot
function in your code and pass in the CSS as a string:
import appendCssToShadowRoot from 'path/to/your/dist/module.js';
appendCssToShadowRoot(`
.my-class {
font-size: 2rem;
}
`, { id: 'my-stylesheet' });
This will append the CSS to the body's shadow root and give the style element an id
of "my-stylesheet".
Asked: 2022-03-01 11:00:00 +0000
Seen: 8 times
Last updated: Jan 17 '22