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

435
Views
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 answers
Answer question

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 Report
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!