title: Set nonce to style tag by code in Webpack
body: <p>Since I want to enable Content Security Policy (CSP) with <code>nonce</code> attribute in style, so I need to set <code>nonce</code> in style dynamically by the code.</p>
  <p>The webpack setting:</p>
  <pre><code>devServer: {
    contentBase: &quot;./dist&quot;,
    watchContentBase: true,
    headers: {
      &quot;Content-Security-Policy&quot;: &quot;style-src 'nonce-test1'&quot;
    }
  }
  </code></pre>
  <p>However, the <code>nonce</code> attribute is generated by server, and will not be the same all the time, so I can not hard coded <code>nonce: test1</code> in <code>style-loader</code>.</p>
  <p>I have found <a href="https://webpack.js.org/loaders/style-loader/#lazystyletag" rel="nofollow noreferrer">lazy loading style</a>, but I have not found articles or tutorials related to set <code>nonce</code> attribute dynamically when <code>&lt;style&gt;</code> is loaded by code.</p>
  <p>How to add <code>nonce</code> to <code>&lt;style&gt;</code> by code?</p>
  <p>index.ts</p>
  <pre><code>import styles from './styles.lazy.css';
  
  export class MyMainClass {
    constructor(nonce) {
      loadStyle(nonce);
    }
  
    private loadStyle(nonce) {
  
      // I need to set nonce before styles are loaded, otherwise csp error will occur.
      styles.setNonceAttribute(nonce)???
  
      styles.use();
    }
  }
  </code></pre>
  <p>webpack.config.js</p>
  <pre><code>module.exports = {
    module: {
      rules: [
        {
          test: /\.lazy\.css$/i,
          use: [
            {
              loader: 'style-loader', 
              options: {
                injectType: 'lazyStyleTag', 
                attributes: {
                  nonce: &quot;initialNonce&quot;
                }
              } 
            },
            'css-loader',
          ],
        },
      ],
    },
  };
  </code></pre>