Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
How to import a node module VS use the browser api?

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).
I use tsc to compile the regular node package and rollup to pack it into a UMD for browser.

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"){
  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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!