Access node crypto or webcrypto in the same file

In a TS package designed to run in both nodeJS and a browser, I want to access secure random generation from either crypto.getRandomValues(browser) or crypto.randomFillSync(node).

In package.json, I have "type": "module", my whole library uses ES6 imports (so require is not defined).

Unfortunately, the node crypto module must be imported to be usable. The import statement cannot “hide” inside if, so it will crash when run in the browser.

if(typeof crypto == "object"){ //we are in a browser
  fillRandom = crypto.getRandomValues
}
else{ //node
  import crypto from "crypto" //Err: Cannot use import outside a module (browser)
  fillRandom = crypto.randomFillSync
}

With commonJS I could simply use require("crypto"), but I have already fully commited to using ESM modules.

I imagine I could swap out this part of the code before compiling TS for browser/node, so both versions would have the code that makes sense in their enviroment, but I don’t know how, it seems a bit overkill.

Is there a way?