1

When I try to access object value from external js file I'm getting this error

TypeError: Cannot read property 'viewport' of undefined

test-diff.js

var GlobalConfigs = require('./global-config.js');
console.log(GlobalConfigs.GlobalConfig.viewport.desktop);

global-config.js

GlobalConfig = {
   viewport: {
        desktop: "960",
        laptop: "320"
    },
    startPage: "10",
    totalPages: "7",
    threshold: "5"
 } 
1
  • Did my answer below help you? Any comments? Commented Dec 27, 2016 at 18:02

3 Answers 3

4

You have to export the object that you want to access with require.

Change:

GlobalConfig = {
   viewport: {
        desktop: "960",
        laptop: "320"
    },
    startPage: "10",
    totalPages: "7",
    threshold: "5"
 } 

to:

exports.GlobalConfig = {
   viewport: {
        desktop: "960",
        laptop: "320"
    },
    startPage: "10",
    totalPages: "7",
    threshold: "5"
};

I would also use numbers instead of strings:

exports.GlobalConfig = {
   viewport: {
        desktop: 960,
        laptop: 320
    },
    startPage: 10,
    totalPages: 7,
    threshold: 5
};

For more details on how modules requiring and exporting works and what's the difference between exports and module.exports see this answer:

For general documentation on modules in Node, see:

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

Comments

0

You should use module.exports. Use this code GlobalConfig = { viewport: { desktop: "960", laptop: "320" }, startPage: "10", totalPages: "7", threshold: "5" } module.exports.GlobalConfig = GlobalConfig;

Comments

0

I agree with other answer listed, however, I think having additional variable might be unnecessary.

module.exports = {
    viewport: {
        desktop: 960,
        laptop: 320
    },
    startPage: 10,
    totalPages: 7,
    threshold: 5
}

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.