Skip to content

Commit

Permalink
Merge pull request #15802 from webpack/fix-nonce
Browse files Browse the repository at this point in the history
add NonceRuntimeModule
  • Loading branch information
sokra committed May 10, 2022
2 parents 3ad4fca + ce56e3b commit ada9c0b
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/RuntimePlugin.js
Expand Up @@ -26,6 +26,7 @@ const GlobalRuntimeModule = require("./runtime/GlobalRuntimeModule");
const HasOwnPropertyRuntimeModule = require("./runtime/HasOwnPropertyRuntimeModule");
const LoadScriptRuntimeModule = require("./runtime/LoadScriptRuntimeModule");
const MakeNamespaceObjectRuntimeModule = require("./runtime/MakeNamespaceObjectRuntimeModule");
const NonceRuntimeModule = require("./runtime/NonceRuntimeModule");
const OnChunksLoadedRuntimeModule = require("./runtime/OnChunksLoadedRuntimeModule");
const PublicPathRuntimeModule = require("./runtime/PublicPathRuntimeModule");
const RelativeUrlRuntimeModule = require("./runtime/RelativeUrlRuntimeModule");
Expand Down Expand Up @@ -431,6 +432,12 @@ class RuntimePlugin {
return true;
}
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.scriptNonce)
.tap("RuntimePlugin", chunk => {
compilation.addRuntimeModule(chunk, new NonceRuntimeModule());
return true;
});
// TODO webpack 6: remove CompatRuntimeModule
compilation.hooks.additionalTreeRuntimeRequirements.tap(
"RuntimePlugin",
Expand Down
24 changes: 24 additions & 0 deletions lib/runtime/NonceRuntimeModule.js
@@ -0,0 +1,24 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Ivan Kopeykin @vankop
*/

"use strict";

const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");

class NonceRuntimeModule extends RuntimeModule {
constructor() {
super("nonce", RuntimeModule.STAGE_ATTACH);
}

/**
* @returns {string} runtime code
*/
generate() {
return `${RuntimeGlobals.scriptNonce} = undefined;`;
}
}

module.exports = NonceRuntimeModule;
5 changes: 5 additions & 0 deletions test/configCases/web/nonce/index.js
@@ -0,0 +1,5 @@
import "./nonce";

it("should set nonce", () => {
expect(__webpack_nonce__).toBe("nonce");
});
1 change: 1 addition & 0 deletions test/configCases/web/nonce/nonce.js
@@ -0,0 +1 @@
__webpack_nonce__ = "nonce";
7 changes: 7 additions & 0 deletions test/configCases/web/nonce/webpack.config.js
@@ -0,0 +1,7 @@
const webpack = require("../../../../");
/** @type {import("../../../../").Configuration} */
module.exports = {
target: "web",
// plugin that intercepts __webpack_require__
plugins: [new webpack.HotModuleReplacementPlugin()]
};

0 comments on commit ada9c0b

Please sign in to comment.