2

In my server.js, I need to check if one variable is true or not in my global.js (with an if statement), but later in that file I have window being used, and window is not defined in server files. This means that I can not require the whole file like so:

var global = require('../client/js/global');

But I would like to do something like this:

require thisSpecificVariable from ('../client/js/global');

There is something called import that imports a specific variable, but is not supported in node 8.

So just to clarify one more time, here is what I am trying to do:

if (this is true) {
    call this function
}

But I am getting an error saying: "Reference Error: window is not defined at bla bla, at bla bla, at bla bla, and etc." Most of these places start with module.

My global.js looks like this (small bit of it as an example):

module.exports = {
    freeMove: true,
    cashing: false,
    gameStarted: false,
    chatHidden: false,

    // Canvas
    screenWidth: window.innerWidth,
    screenHeight: window.innerHeight,
}

Is it possible to reference one specific variable or ignore the ones that include window? And how do I do it?

1 Answer 1

2

You can get just one item from the exported object like this:

var gameStarted = require('../client/js/global').gameStarted;

But, if you're trying to run this module in an environment that does not have the window object defined, this will still generate an error because the whole module is initialized regardless of which exact exports you want. To fix that, you will have to fix global.js itself so that it does not try to reference window when it is not defined.

For example, you could do this in your global.js:

module.exports = {
    freeMove: true,
    cashing: false,
    gameStarted: false,
    chatHidden: false,
};

if (typeof window !== "undefined") {
    module.exports.screenWidth = window.innerWidth;
    module.exports.screenHeight = window.innerHeight;
}

Then, you won't attempt to reference the window object when it does not exist (presumably when you're running from node.js instead of a browser).

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.