我有一个带有以下内容的javascript文件journal.js:
require('./fixtures/journal-data');
if (typeof module != "undefined" && module.exports)
module.exports = JOURNAL;
var hasEvent = function hasEvent(event, entry) {
return entry.events.indexOf(event) != -1;
};
var tableFor = function tableFor(event, journal) {
var table = [0, 0, 0, 0];
for (var i = 0; i < journal.length; i++) {
var entry = journal[i], index = 0;
if (hasEvent(event, entry)) index += 1;
if (entry.squirrel) index += 2;
table[index] += 1;
}
return table;
};
console.log(tableFor("pizza", JOURNAL));
当我运行此文件时,我得到:
ReferenceError: JOURNAL is not defined
在Node我可以看到,外部javascript文件journal-data已加载。
我在这里缺少什么?
编辑: 期刊数据文件的内容是:
// journal-data.js
var JOURNAL = [
{"events":["carrot","exercise","weekend"],"squirrel":false},
{"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false}
];
答案 0 :(得分:2)
您需要从文件中导出JOURNAL var,如下所示。
exports.JOURNAL = [
{"events": ['carrot', ...]}
]
这将允许您在其当前状态下使用您的journal.js.
另外,您可以使用以下语法:
<强> ./夹具/日志数据强>
module.exports = [ {"events": [...]} ];
<强> ./ journal.js 强>
var JOURNAL = require('./fixtures/journal-data');
....