Skip to content

Commit e6e7dd6

Browse files
authored
Merge pull request #234 from mjhanninen/fix-webpack-dynamic-require-error
Fix Webpack warning caused by dynamic require
2 parents b9c7c0c + 8fad7c5 commit e6e7dd6

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/js.rs

+11-3
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,15 @@ extern "C" {
102104
#[wasm_bindgen(method, js_name = getRandomValues, catch)]
103105
fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
104106

107+
// We use a "module" object here instead of just annotating require() with
108+
// js_name = "module.require", so that Webpack doesn't give a warning. See:
109+
// https://github.com/rust-random/getrandom/issues/224
110+
type NodeModule;
111+
#[wasm_bindgen(js_name = module)]
112+
static NODE_MODULE: NodeModule;
105113
// 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>;
114+
#[wasm_bindgen(method, catch)]
115+
fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>;
108116
type NodeCrypto;
109117
#[wasm_bindgen(method, js_name = randomFillSync, catch)]
110118
fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;

0 commit comments

Comments
 (0)