Skip to content

Commit 8372c16

Browse files
committed
Fix Webpack warning caused by dynamic require
Webpack supports dynamic importing only for some special cases in which it is able to narrow down the set of packages to bundled. In the general case it just produces an empty (Webpack) context plus the warning stating that "the request of a dependency is an expression." Apparently the commit 120a1d7 changed the Javascript generated by wasm-bindgen so that the binding for the `require` became: ``` module.require(getStringFromWasm0(arg0, arg1)) ``` when it used to be: ``` getObject(arg0).require(getStringFromWasm0(arg1, arg2)) ``` In the latter case Webpack did not even realize that this code imported a package and, hence, did not try to bundle it. The new code triggers the bundling and because the dependency is fully dynamic Webpack has problems with it. This commit reverts partially the commit 120a1d7 so that the generated binding obfuscates the `require` call enough to hide it from Webpack again.
1 parent 0d0404b commit 8372c16

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/js.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,9 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
5959
fn getrandom_init() -> Result<RngSource, Error> {
6060
let global: Global = global().unchecked_into();
6161
if is_node(&global) {
62-
let crypto = require("crypto").map_err(|_| Error::NODE_CRYPTO)?;
62+
let crypto = NODE_MODULE
63+
.require("crypto")
64+
.map_err(|_| Error::NODE_CRYPTO)?;
6365
return Ok(RngSource::Node(crypto));
6466
}
6567

@@ -102,9 +104,12 @@ extern "C" {
102104
#[wasm_bindgen(method, js_name = getRandomValues, catch)]
103105
fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
104106

107+
type NodeModule;
108+
#[wasm_bindgen(js_name = module)]
109+
static NODE_MODULE: NodeModule;
105110
// Node JS crypto module (https://nodejs.org/api/crypto.html)
106-
#[wasm_bindgen(catch, js_name = "module.require")]
107-
fn require(s: &str) -> Result<NodeCrypto, JsValue>;
111+
#[wasm_bindgen(method, catch)]
112+
fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>;
108113
type NodeCrypto;
109114
#[wasm_bindgen(method, js_name = randomFillSync, catch)]
110115
fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;

0 commit comments

Comments
 (0)