diff --git a/lib/addStyles.js b/lib/addStyles.js index c0767b01..4ae1917f 100644 --- a/lib/addStyles.js +++ b/lib/addStyles.js @@ -205,6 +205,13 @@ function createStyleElement (options) { options.attrs.type = "text/css"; } + if(options.attrs.nonce === undefined) { + const nonce = getNonce(); + if (nonce) { + options.attrs.nonce = nonce; + } + } + addAttrs(style, options.attrs); insertStyleElement(options, style); @@ -231,6 +238,14 @@ function addAttrs (el, attrs) { }); } +function getNonce() { + if (typeof __webpack_nonce__ === 'undefined') { + return null; + } + + return __webpack_nonce__; +} + function addStyle (obj, options) { var style, update, remove, result; diff --git a/test/basic.test.js b/test/basic.test.js index 3725e962..cd2713e6 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -220,6 +220,27 @@ describe("basic tests", function() { runCompilerTest(expected, done); }); // it attrs + it("nonce", function(done) { + // Setup + const expectedNonce = "testNonce"; + + fs.writeFileSync( + rootDir + "main.js", + [ + `__webpack_nonce__ = '${expectedNonce}'`, + "var a = require('./style.css');" + ].join("\n") + ); + + // Run + let expected = [ + existingStyle, + `` + ].join("\n"); + + runCompilerTest(expected, done); + }); // it attrs + it("type attribute", function(done) { // Setup styleLoaderOptions.attrs = {type: 'text/less'};