fix: support `__webpack_nonce__` for CSS chunks

This commit is contained in:
alexander.akait 2024-02-27 20:27:45 +03:00
parent 5c2abc3734
commit 9c2bf0c52e
6 changed files with 40 additions and 0 deletions

View File

@ -114,6 +114,11 @@ class CssLoadingRuntimeModule extends RuntimeModule {
const code = Template.asString([
"link = document.createElement('link');",
`if (${RuntimeGlobals.scriptNonce}) {`,
Template.indent(
`link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
),
"}",
uniqueName
? 'link.setAttribute("data-webpack", uniqueName + ":" + key);'
: "",

View File

@ -0,0 +1,3 @@
.class {
color: red;
}

View File

@ -0,0 +1 @@
function test() {}

View File

@ -3,3 +3,25 @@ import "./nonce";
it("should set nonce", () => {
expect(__webpack_nonce__).toBe("nonce");
});
it("should set nonce attributes", () => {
import(/* webpackChunkName: "chunk-js" */ "./chunk.js");
expect(document.head._children).toHaveLength(1);
const script = document.head._children[0];
expect(script._type).toBe("script");
expect(script.getAttribute("nonce")).toBe("nonce");
expect(script.src).toBe("https://example.com/chunk-js.js");
import(/* webpackChunkName: "chunk-css" */ "./chunk.css");
expect(document.head._children).toHaveLength(2);
const link = document.head._children[1];
expect(link._type).toBe("link");
expect(link.getAttribute("nonce")).toBe("nonce");
expect(link.href).toBe("https://example.com/chunk-css.css");
});

View File

@ -1 +1,2 @@
__webpack_nonce__ = "nonce";
__webpack_public_path__ = "https://example.com/";

View File

@ -2,6 +2,14 @@ const webpack = require("../../../../");
/** @type {import("../../../../").Configuration} */
module.exports = {
target: "web",
output: {
publicPath: "",
filename: "bundle0.mjs",
chunkFilename: "[name].js"
},
experiments: {
css: true
},
// plugin that intercepts __webpack_require__
plugins: [new webpack.HotModuleReplacementPlugin()]
};