Skip to content

Commit

Permalink
Merge pull request #234 from mjhanninen/fix-webpack-dynamic-require-e…
Browse files Browse the repository at this point in the history
…rror

Fix Webpack warning caused by dynamic require
  • Loading branch information
josephlr committed Jan 14, 2022
2 parents b9c7c0c + 8fad7c5 commit e6e7dd6
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/js.rs
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,15 @@ extern "C" {
#[wasm_bindgen(method, js_name = getRandomValues, catch)]
fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;

// We use a "module" object here instead of just annotating require() with
// js_name = "module.require", so that Webpack doesn't give a warning. See:
// https://github.com/rust-random/getrandom/issues/224
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 e6e7dd6

Please sign in to comment.