Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda