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

446
Visualizações
Typescript + webpack: Check for variable that is not defined in Node, but defined in Browser

I am trying to write a package for server and client use with as little modification as needed.

Some libs are part of Node but not included in a browser, others are available in a browser but not in Node.

Using https://github.com/lmaccherone/node-localstorage for example, I want to require the library when on Node, but in a browser, localStorage is already available.

I would like to check whether localStorage is available with a declare statement found in https://stackoverflow.com/a/65755447/2875404 so it looks like that:

declare var localStorage: any | undefined;

if (typeof localStorage === "undefined" || localStorage === null) {
    console.log("need to use Node localStorage")
    var LocalStorage = require('node-localstorage').LocalStorage;
    var localStorage = new LocalStorage('./localStorage');
  } else {
    console.log("using Browser localStorage")
  }  

After wrapping up the package in webpack and, for a test, running it in a Chrome snippet, the "need to use Node localStorage" message pops up in console. If I manually edit the webpack'd code to console.log(localStorage) it actually does print the localStorage (so it must be there) - additionally, when I remove the whole if (typeof... block, the code accessing localStorage seems to run just fine.

What exactly do I need to do to make this "hybrid decision" function work? Can this have to do with webpack somehow putting things into a "deeper" scope that doesn't have access to window variables such as localStorage? But why is it possible to print and interact with the class then? I'm confused.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As I said in the comment, you could use the global window to check if you're in browser context:

declare var localStorage: any | undefined;

if (typeof window === 'undefined') {
    console.log("need to use Node localStorage")
    var LocalStorage = require('node-localstorage').LocalStorage;
    var localStorage = new LocalStorage('./localStorage');
} else {
    console.log("using Browser localStorage")
}
about 4 years ago · Juan Pablo Isaza Relatório
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