__webpack_nonce__ fails due to imports getting hoisted above the assignment.
See original GitHub issueBug report
What is the current behavior?
I’m attempting to setup CSP in our application, and the __webpack_nonce__
assignment simply isn’t working. After digging into the generated code, I discovered it’s because all of the imports get hoisted above the assignment value, and thus get loaded before it ever gets set.
// entry.js
__webpack_nonce__ = "foo";
import { createRoot } from 'react-dom/client';
import App from './App';
const element = document.getElementById('root');
const root = createRoot(element);
root.render(<App />);
This produces the following:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var react_dom_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom/client */ "./node_modules/react-dom/client.js");
/* harmony import */ var _App__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./App */ "./src/App.js");
/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react/jsx-runtime */ "./node_modules/react/jsx-runtime.js");
__webpack_require__.nc = "foo";
const element = document.getElementById('root');
const root = (0,react_dom_client__WEBPACK_IMPORTED_MODULE_1__.createRoot)(element);
root.render( /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_3__.jsx)(_App__WEBPACK_IMPORTED_MODULE_2__["default"], {}));
I can confirm that at every invocation of a script include, __webpack_require__.nc
is undefined because it executed before the assignment.
What is the expected behavior?
I expect to be able to set the nonce, per the documentation, and have it be attached to the script tags that the runtime produces.
Other relevant information: webpack version: 5.72.0 Node.js version: 16.14.0 Operating System: macOS 12.3 Additional tools: React 18, babel 7
Issue Analytics
- State:
- Created a year ago
- Comments:8 (5 by maintainers)
Top GitHub Comments
yeah, got a problem. I’ll fix this
Reproduction repo here: https://github.com/Twipped/webpack-nonce-repro
npm install
andnpm start
should pop open a browser window that demonstrates the issue. If you use the console to navigate toload script
and break at the check the value of__webpack_require__.nc
on line 20, you’ll see it’s undefined, whilewindow.NONCE
does have a value present.