0

What am I doing wrong here? I define a variable in FILE1, then require FILE1 in FILE2, and I require FILE2 in MAIN, so I expected to be able to access the global var my_global from both MAIN and FILE2 but it throws an error.

FILE1

var my_global=42;

FILE2

require('FILE1');
var harvesterCount=12;
console.log(harvesterCount+my_global); //throws error
module.exports = function () {...}

MAIN

require('FILE2');
console.log(my_global); //error here

The error statement (from Screeps console):

ReferenceError: my_global is not defined
    at module.exports:8:5
    at Object.module.exports.loop:6:5
    at __mainLoop:1:12057
    at eval:2:4
    at Object.c.runCode:6:26869
Rilcon42
  • 9,584
  • 18
  • 83
  • 167

2 Answers2

0

Try to reference the file using <script> tag rather than using require

And I see in another answer from stackoverflow about require. Hope this can help you.

require() is not part of your standard JavaScript. In context to your question and tags, require() is built into Node.js to load modules. The concept is similar to C/Java/Python/[insert more languages here] imports or includes.

The concept of modules is similar to just adding small bits of JavaScript code via a tags. Unlike adding a tag, it doesn't leak the file into the global scope

Community
  • 1
  • 1
Iswanto San
  • 18,263
  • 13
  • 58
  • 79
  • Thanks to your post I found the answer here: http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it/5311377#5311377 I had to export the global variable – Rilcon42 Mar 22 '16 at 04:57
  • You can't make use of ` – CuriousMind Mar 22 '16 at 05:02
0

The behavior is correct and you should rather export the variable. For e.g.

var my_global=42;
exports = {
  my_global:my_global
}

You can reference the above exported variable using

var m = require('file1');
console.log(m.my_global);
CuriousMind
  • 3,143
  • 3
  • 29
  • 54