1

I need to have some config object both in the node app and in the browser. Here is the path and the content of the config:

path: [app]/public/js/config.js
content:

var config = {
    "foo": "bar",
    "num": 42,
    "list": ["a","b","f"]
};
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
if(!isBrowser) {
    module.exports = config;
}

In my html I just add a script element and it works fine:

<script src="/js/config.js"></script>

In node app however I do not seem to have imported the object and I get an empty object:

var config = require('./public/js/config.js');
console.log('config:', config); // gives config: {}

What am I doing wrong?

Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127

3 Answers3

3

Your isBrowser variable is assigned a function, but it is never executed.

Therefore it does not perform any environment detection.

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • Thanks! That part was borrowed (read copied) from [this answer](https://stackoverflow.com/a/31090240/66580) but I missed the function call part. Changing `if(!isBrowser) {` to `if(!isBrowser()) {` resolved the issue. – Majid Fouladpour Nov 14 '17 at 09:47
1

The code should have been

if(!isBrowser()) {
    module.exports = config;
}

isBrowser is a function here. Since in your version !isBrowser always return false so module.exports = config is never executed.

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
1

Replace if block

if(!isBrowser) {
    module.exports = config;
}

to

if(!isBrowser()) {//this isBrowser() function
    module.exports = config;
}
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51