rslib icon indicating copy to clipboard operation
rslib copied to clipboard

[Bug]: `__webpack_nonce__` should not be transformed

Open meyer opened this issue 6 months ago • 4 comments

Version

System:
    OS: macOS 15.3.2
    CPU: (12) arm64 Apple M2 Pro
    Memory: 181.52 MB / 32.00 GB
    Shell: 4.0 - /opt/homebrew/bin/fish
  Browsers:
    Chrome: 136.0.7103.114
    Safari: 18.3.1
  npmPackages:
    @rslib/core: ^0.7.1 => 0.7.1

Details

I’m testing out rslib in a library I maintain. In the library, I use __webpack_nonce__ to provide a nonce for dynamically-inserted style tags.

The following code

declare const __webpack_nonce__: string | undefined;

const styleElement = document.createElement('style');
if (typeof __webpack_nonce__ !== 'undefined') {
  styleElement.nonce = __webpack_nonce__;
}
styleElement.appendChild(document.createTextNode('/* jsxstyle */'));
document.head.appendChild(styleElement);

is transformed to this:

var __webpack_require__ = {};
(()=>{
    __webpack_require__.nc = void 0;
})();

const styleElement = document.createElement('style');
styleElement.nonce = __webpack_require__.nc;
styleElement.appendChild(document.createTextNode('/* jsxstyle */'));
document.head.appendChild(styleElement);

but I would expect to see this instead:

const styleElement = document.createElement('style');
if (typeof __webpack_nonce__ !== 'undefined') {
  styleElement.nonce = __webpack_nonce__;
}
styleElement.appendChild(document.createTextNode('/* jsxstyle */'));
document.head.appendChild(styleElement);

so that I can set __webpack_nonce__ in code that uses this library.

Reproduce link

https://github.com/jsxstyle/jsxstyle/tree/rslib

Reproduce Steps

  1. Add __webpack_nonce__ to a library
  2. Bundle the library with rslib

meyer avatar May 18 '25 18:05 meyer

You can use source.define like '_WEBPACK_NONCE_': '__webpack_nonce__' to preserve the internal variables. Remember to change your source code either.

Timeless0911 avatar May 19 '25 02:05 Timeless0911

@Timeless0911 Should this be the default behavior of Rslib, or can we add guidance in the documentation?

chenjiahan avatar May 19 '25 03:05 chenjiahan

Yeah, the best solution is to preserve webpack variables automatically in Rslib but we have not find a way to achieve it. I will add some guides to docs soon.

Timeless0911 avatar May 19 '25 03:05 Timeless0911

You can use source.define like '_WEBPACK_NONCE_': '__webpack_nonce__' to preserve the internal variables. Remember to change your source code either.

@Timeless0911 nice, thank you! I’ll give that a go in the mean time.

meyer avatar May 21 '25 21:05 meyer