diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index 911798d42d482e..afd98becafb83d 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -395,6 +395,7 @@ if ('document' in globalThis) { // all css imports should be inserted at the same position // because after build it will be a single css file let lastInsertedStyle: HTMLStyleElement | undefined +let cspNonce: string | undefined | null = undefined export function updateStyle(id: string, content: string): void { let style = sheetsMap.get(id) @@ -404,6 +405,15 @@ export function updateStyle(id: string, content: string): void { style.setAttribute('data-vite-dev-id', id) style.textContent = content + if (cspNonce === undefined) { + cspNonce = + document.querySelector('meta[property=csp-nonce]') + ?.nonce ?? null + } + if (cspNonce) { + style.setAttribute('nonce', cspNonce) + } + if (!lastInsertedStyle) { document.head.appendChild(style) diff --git a/playground/css/__tests__/css.spec.ts b/playground/css/__tests__/css.spec.ts index b424faace62b81..eb55a5dd88e052 100644 --- a/playground/css/__tests__/css.spec.ts +++ b/playground/css/__tests__/css.spec.ts @@ -6,6 +6,7 @@ import { getBg, getColor, isBuild, + isServe, page, removeFile, serverLogs, @@ -508,3 +509,8 @@ test('async css order with css modules', async () => { test('@import scss', async () => { expect(await getColor('.at-import-scss')).toBe('red') }) + +test.runIf(isServe)('style csp nonce', async () => { + const cspNonce = await page.getAttribute('style', 'nonce') + expect(cspNonce).toBe('random') +}) diff --git a/playground/css/index.html b/playground/css/index.html index 2016c1b3c72ca8..f33bed05bb6648 100644 --- a/playground/css/index.html +++ b/playground/css/index.html @@ -1,3 +1,5 @@ + +