Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

443
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda