1

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.

2
  • 1
    Check for window global instead? Commented Sep 12, 2021 at 22:13
  • 1
    @Dominik you are the best. I check for window and access the variable as window.localStorage now. Write as answer please so I can tick. Commented Sep 12, 2021 at 22:47

1 Answer 1

1

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")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.