简体   繁体   中英

Javascript load external file: ReferenceError: JOURNAL is not defined

i have a javascript file journal.js with this content:

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));

when i run this file i get:

ReferenceError: JOURNAL is not defined

In Node i can see, that the external javascript file journal-data is loaded.

What am i missing here?

EDIT: The content of the journal-data file is:

// journal-data.js
var JOURNAL = [
  {"events":["carrot","exercise","weekend"],"squirrel":false},
  {"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false}
];

You need to export the JOURNAL var from your file, like this.

exports.JOURNAL = [
  {"events": ['carrot', ...]}
]

This will allow you to use your journal.js in it's current state.

Alteratively you can use the following syntax instead:

./fixtures/journal-data

module.exports = [ {"events": [...]} ];

./journal.js

var JOURNAL = require('./fixtures/journal-data');
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM