我在constants.js文件中有以下代码:
var constants = (
conversationUsername: "user1",
conversationPassword: "pass1",
conversationVersionDate: "date1",
conversationWorkspaceId: "work1"
};
module.exports.constants = constants;
现在,在另一个文件中,我有以下内容:
var constants = require('./../constants');
console.log(constants);
哪个输出我:
{ constants:
{ conversationUsername: 'user1',
conversationPassword: 'pass1',
conversationVersionDate: 'date1',
conversationWorkspaceId: 'work1' } }
我猜,我还好。
我的问题是,我现在如何访问这些字段?如果我尝试:
console.log(constants.conversationUsername);
我明白了:
未定义
答案 0 :(得分:4)
首先访问其constants
字段
console.log(constants.constants.conversationUsername);
直接或export
该对象
module.exports = constants;
答案 1 :(得分:2)
另一种快速解决方案是从导入中提取属性:
var constants = require('./../constants').constants
或短
var {constants} = require('./../constants')
然后按预期访问属性:
constants.conversationUsername