Skip to content

Commit

Permalink
Fix Webpack warning caused by dynamic require
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mjhanninen committed Oct 15, 2021
1 parent 0d0404b commit 8372c16
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
fn getrandom_init() -> Result<RngSource, Error> {
let global: Global = global().unchecked_into();
if is_node(&global) {
let crypto = require("crypto").map_err(|_| Error::NODE_CRYPTO)?;
let crypto = NODE_MODULE
.require("crypto")
.map_err(|_| Error::NODE_CRYPTO)?;
return Ok(RngSource::Node(crypto));
}

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

type NodeModule;
#[wasm_bindgen(js_name = module)]
static NODE_MODULE: NodeModule;
// Node JS crypto module (https://nodejs.org/api/crypto.html)
#[wasm_bindgen(catch, js_name = "module.require")]
fn require(s: &str) -> Result<NodeCrypto, JsValue>;
#[wasm_bindgen(method, catch)]
fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>;
type NodeCrypto;
#[wasm_bindgen(method, js_name = randomFillSync, catch)]
fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;
Expand Down

0 comments on commit 8372c16

Please sign in to comment.