如何解决通过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',],},};
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。