Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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<HTMLMetaElement>('meta[property=csp-nonce]')
?.nonce ?? null
}
if (cspNonce) {
style.setAttribute('nonce', cspNonce)
}

if (!lastInsertedStyle) {
document.head.appendChild(style)

Expand Down
6 changes: 6 additions & 0 deletions playground/css/__tests__/css.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getBg,
getColor,
isBuild,
isServe,
page,
removeFile,
serverLogs,
Expand Down Expand Up @@ -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')
})
2 changes: 2 additions & 0 deletions playground/css/index.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<meta property="csp-nonce" nonce="random" />

<link rel="stylesheet" href="./linked.css" />

<div class="wrapper">
Expand Down