2016-06-28 137 views
0

我有以下的配置文件:Error屬性未定義

/* 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) 

我還想保留一個文件,而不是創建第二個文件。 我該如何解決這個問題?

+0

[在對象字面聲明自我引用(http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) –

+0

謝謝,但答案可能的複製@ user1280859它更適合我:) –

回答

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 */