Skip to content

__webpack_nonce__ fails due to imports getting hoisted above the assignment. #15776

@Twipped

Description

@Twipped

Bug 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions