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?

4
  • you need module.exports = in the config.js for require to work? Commented Nov 14, 2017 at 9:36
  • Why not using a standard UMD instead of the above function trick? Commented Nov 14, 2017 at 9:36
  • @AnthonyKong, I do have module.exports = in the config.js. Commented Nov 14, 2017 at 9:38
  • @ghybs, I'll test that to see if it takes care of the issue. Thanks. Commented Nov 14, 2017 at 9:39

3 Answers 3

3

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

Therefore it does not perform any environment detection.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That part was borrowed (read copied) from this answer but I missed the function call part. Changing if(!isBrowser) { to if(!isBrowser()) { resolved the issue.
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.

Comments

1

Replace if block

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

to

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

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.