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.
CodePudding user response:
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")
}