指向局部变量时未定义的错误属性

时间:2016-06-28 09:17:11

标签: javascript node.js variables configuration scope

我有以下配置文件:

/* env.js */

ENV_TO_USE = [
"local"
];

// local; dev; rec; pre; prod
module.exports = {
    env_properties : {
        local : {
            root_url : "localhost",
            port : 3000,
            root_dir : "/home/user/project/"
        },
        dev : {
            root_url : "devdomain",
            port : 3000,
            root_dir : "/apps/project/",
        }
    },
    global_properties : {
        path_include :
        {
            PATH_EXPRESS : env_properties[ENV_TO_USE].root_dir + 'express'
        }
    }
};

在另一个档案中,我想要打印“PATH_EXPRESS”。价值:

/* test.js */

var env = require('./env.js');
console.log(env.global_properties.path_include.PATH_EXPRESS);

但是当我使用命令 node test.js 启动脚本时,我收到以下错误:

PATH_EXPRESS : env_properties[ENV_TO_USE].root_dir + 'express'
                       ^
ReferenceError: env_properties is not defined
at Object.<anonymous> (C:\cygwin64\home\user\project\env.js:23:21)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (C:\cygwin64\home\user\project\test.js:1:73)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)

我仍然希望保留一个文件,而不是创建第二个文件。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

/* env.js */
ENV_TO_USE = [
"local"
];

var env_properties = {
        local : {
            root_url : "localhost",
            port : 3000,
            root_dir : "/home/user/project/"
        },
        dev : {
            root_url : "devdomain",
            port : 3000,
            root_dir : "/apps/project/",
        }
    }

// local; dev; rec; pre; prod
module.exports = {
    env_properties : env_properties,
    global_properties : {
        path_include :
        {
            // and you have to specify which env you want to use
            PATH_EXPRESS : env_properties[0].root_dir + 'express'
        }
    }
};
/* No need to export the env_properties since it is included in the scope */