Skip to content

Commit fc24512

Browse files
iamdavidfrancisevilebottnawi
authored andcommitted
feat: add support for __webpack_nonce__ (#319)
1 parent c7d8fec commit fc24512

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

lib/addStyles.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,13 @@ function createStyleElement (options) {
208208
options.attrs.type = "text/css";
209209
}
210210

211+
if(options.attrs.nonce === undefined) {
212+
const nonce = getNonce();
213+
if (nonce) {
214+
options.attrs.nonce = nonce;
215+
}
216+
}
217+
211218
addAttrs(style, options.attrs);
212219
insertStyleElement(options, style);
213220

@@ -234,6 +241,14 @@ function addAttrs (el, attrs) {
234241
});
235242
}
236243

244+
function getNonce() {
245+
if (typeof __webpack_nonce__ === 'undefined') {
246+
return null;
247+
}
248+
249+
return __webpack_nonce__;
250+
}
251+
237252
function addStyle (obj, options) {
238253
var style, update, remove, result;
239254

test/basic.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,27 @@ describe("basic tests", function() {
244244
runCompilerTest(expected, done);
245245
}); // it attrs
246246

247+
it("nonce", function(done) {
248+
// Setup
249+
const expectedNonce = "testNonce";
250+
251+
fs.writeFileSync(
252+
rootDir + "main.js",
253+
[
254+
`__webpack_nonce__ = '${expectedNonce}'`,
255+
"var a = require('./style.css');"
256+
].join("\n")
257+
);
258+
259+
// Run
260+
let expected = [
261+
existingStyle,
262+
`<style type="text/css" nonce="${expectedNonce}">${requiredCss}</style>`
263+
].join("\n");
264+
265+
runCompilerTest(expected, done);
266+
}); // it attrs
267+
247268
it("type attribute", function(done) {
248269
// Setup
249270
styleLoaderOptions.attrs = {type: 'text/less'};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy