通过Webpack中的代码将随机数设置为样式标签

问题描述

由于我想使用样式中的nonce属性启用内容安全策略(CSP),因此我需要通过代码动态设置nonce样式。

webpack设置:

devServer: {
  contentBase: "./dist",watchContentBase: true,headers: {
    "Content-Security-Policy": "style-src 'nonce-test1'"
  }
}

但是,nonce属性是由服务器生成的,并且不会一直相同,因此无法在nonce: test1中对style-loader进行硬编码。

我找到了lazy loading style,但是当通过代码加载nonce时,我没有找到与动态设置<style>相关的文章或教程。

如何通过代码将nonce添加到<style>

index.ts

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();
  }
}

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.lazy\.css$/i,use: [
          {
            loader: 'style-loader',options: {
              injectType: 'lazyStyleTag',attributes: {
                nonce: "initialNonce"
              }
            } 
          },'css-loader',],},};

解决方法

在Webpack的下一页-There are two ways to work with nonce

  • 使用属性选项
  • 使用 webpack_nonce 变量 和代码示例。

还是您的情况不起作用?

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...