Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(addStyles): add support for __webpack_nonce__ #319

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/addStyles.js
Expand Up @@ -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);

Expand All @@ -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;

Expand Down
21 changes: 21 additions & 0 deletions test/basic.test.js
Expand Up @@ -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,
`<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