0

I previously included other js files into my node projects using require as seen on this post. But for some reason this no longer works, did Node change or am I missing some mistake?

This is my code:

main.js:

require("./test");

console.log(x);

test.js:

var x = 3;

Running this code results in this error message:

main.js:3
console.log(x);
            ^

ReferenceError: x is not defined
user11914177
  • 885
  • 11
  • 33

4 Answers4

2

Well, you need to add this - test.js:

const x = 3;
module.exports = x;

main.js:

const x = require('./test.js');
console.log(x);

And documentation: https://nodejs.org/api/modules.html

Itamar Cohen
  • 340
  • 4
  • 15
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 22 '21 at 12:52
1

You can't use variable declare in the required file without exporting variables.

More document about export

test.js:

var x = 3;

module.exports.x = x;

main.js:

var test = require("./test");

console.log(test.x);
Pooya
  • 2,968
  • 2
  • 12
  • 18
0

Looking at an other project I found what I wanted:

test.js:

global.x = 3;

main.js:

require("./test");

console.log(x);
user11914177
  • 885
  • 11
  • 33
0

you need to export var from test.js

export var x = 3;

after that import into main.js

var { x } = require("./test");
console.log(x);