Ask Your Question
4

What is the process for creating a module utilizing esbuild and the esbuild-css-modules-plugin to append css to body.shadowRoot?

asked 2022-03-01 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-01-17 04:00:00 +0000

woof gravatar image

Here are the steps to create a module utilizing esbuild and the esbuild-css-modules-plugin to append css to body.shadowRoot:

  1. Install the required modules:

    npm install esbuild esbuild-css-modules-plugin --save-dev
    
  2. 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;
    
  3. 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]',
       }),
     ],
    });
    
  4. Include the compiled module file in your HTML file:

    <script src="path/to/your/dist/module.js"></script>
    
  5. 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".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-01 11:00:00 +0000

Seen: 8 times

Last updated: Jan 17 '22