title: Inject CSS Modules to Per-Component Style Elements (for portability to shadow root)
body: <h2>TL:DR</h2>
  <p>How can I get CSS of React components to work inside of a shadow root, while keeping the
  encapsulation benefits of CSS Modules class? I'd like to insert per-component <code>&lt;style&gt;</code> elements instead of inside of <code>&lt;head&gt;</code> or another arbitrary element.</p>
  <h2>What I have</h2>
  <p>I'm currently using CSS Modules in React with a custom Webpack script; <code>[style-loader, css-loader, sass-loader]</code> in the traditional way. The resulting compiled CSS is injected as <code>&lt;style&gt;</code> tags in <code>head</code>.</p>
  <pre><code>
      // MyComponent.jsx
      import React from 'react';
      import styles from './MyComponent.scss';
  
      export const MyComponent = () =&gt; {
        return &lt;div className={styles.container}&gt;Hello!&lt;/div&gt;
      }
  
      // MyComponent.scss
      .container {
        background: purple;
      }
  
  </code></pre>
  <h3>result</h3>
  <pre><code>    &lt;!-- rendered page --&gt;
      &lt;head&gt;
        ...
        &lt;style&gt;.myComponent__container__hash123 { background: purple }&lt;/style&gt;
      &lt;/head&gt;
      &lt;body&gt;
        ...
        &lt;div class=&quot;myComponent__container__hash123&quot;&gt;Hello!&lt;/div&gt;
      &lt;/body&gt;
  
  </code></pre>
  <h2>What I want</h2>
  <p>For use inside of a shadow root, I would like to instead inject each component's compiled CSS into a <code>&lt;style&gt;</code> tag on its root.</p>
  <pre><code>    &lt;!-- rendered page --&gt;
      &lt;head&gt;
        ...
      &lt;/head&gt;
      &lt;body&gt;
        ...
        &lt;div&gt;
          #shadow-root
            &lt;div class=&quot;myComponent__container__hash123&quot;&gt;Hello!&lt;/div&gt;
            &lt;style&gt;.myComponent__container__hash123 { background: purple }&lt;/style&gt;
          #end shadow-root
        &lt;/div&gt;
      &lt;/body&gt;
  </code></pre>
  <h2>What I tried</h2>
  <h3>1. insert</h3>
  <p>This will not work for component libraries which compile themselves, where I cannot know the end consumer in advance.</p>
  <h3>2. <code>to-string-loader</code></h3>
  <p><a href="https://www.npmjs.com/package/css-to-string-loader" rel="noreferrer">https://www.npmjs.com/package/css-to-string-loader</a></p>
  <p>When combined with <code>style-loader</code>, the result is classnames aren't resolved (e.g. <code>styles.container === undefined</code>).</p>
  <hr />
  <p>Ideally I would have <code>import styles from './MyComponent'</code> contain the compiled CSS string in addition to classname mapping - however this is not supported as per <a href="https://github.com/webpack-contrib/style-loader" rel="noreferrer">style-loader docs</a></p>