diff --git a/src/hooks/useStyleRegister.tsx b/src/hooks/useStyleRegister.tsx index d36f051..6dd2a7d 100644 --- a/src/hooks/useStyleRegister.tsx +++ b/src/hooks/useStyleRegister.tsx @@ -336,7 +336,7 @@ export default function useStyleRegister( path: string[]; hashId?: string; layer?: string; - nonce?: string; + nonce?: string | (() => string); }, styleFn: () => CSSInterpolation, ) { @@ -385,8 +385,10 @@ export default function useStyleRegister( attachTo: container, }; - if (nonce) { - mergedCSSConfig.csp = { nonce }; + const nonceStr = typeof nonce === 'function' ? nonce() : nonce; + + if (nonceStr) { + mergedCSSConfig.csp = { nonce: nonceStr }; } const style = updateCSS(styleStr, styleId, mergedCSSConfig); diff --git a/tests/index.spec.tsx b/tests/index.spec.tsx index 237744f..45056b1 100644 --- a/tests/index.spec.tsx +++ b/tests/index.spec.tsx @@ -411,24 +411,31 @@ describe('csssinjs', () => { expect(container.querySelectorAll('style')).toHaveLength(1); }); - it('nonce', () => { - const NonceBox = () => { - useStyleRegister( - { theme, token: {}, path: ['.nonce'], nonce: 'bamboo' }, - () => [], - ); - - return
; - }; - - render( - - - , - ); + describe('nonce', () => { + function test(name: string, nonce: string | (() => string)) { + it(name, () => { + const NonceBox = () => { + useStyleRegister( + { theme, token: {}, path: ['.nonce'], nonce }, + () => [], + ); + + return
; + }; + + render( + + + , + ); + + const styles = Array.from(document.head.querySelectorAll('style')); + expect(styles).toHaveLength(1); + expect(styles[0].nonce).toBe('bamboo'); + }); + } - const styles = Array.from(document.head.querySelectorAll('style')); - expect(styles).toHaveLength(1); - expect(styles[0].nonce).toBe('bamboo'); + test('string', 'bamboo'); + test('function', () => 'bamboo'); }); });