Skip to content

Commit

Permalink
feat: add support for __webpack_nonce__ (#319)
Browse files Browse the repository at this point in the history
  • Loading branch information
iamdavidfrancis authored and evilebottnawi committed Jun 1, 2018
1 parent c7d8fec commit fc24512
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/addStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,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);

Expand All @@ -234,6 +241,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;

Expand Down
21 changes: 21 additions & 0 deletions test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,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,
`<style type="text/css" nonce="${expectedNonce}">${requiredCss}</style>`
].join("\n");

runCompilerTest(expected, done);
}); // it attrs

it("type attribute", function(done) {
// Setup
styleLoaderOptions.attrs = {type: 'text/less'};
Expand Down

0 comments on commit fc24512

Please # to comment.