Home > other >  Did node require change?
Did node require change?

Time:12-22

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

CodePudding user response:

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

CodePudding user response:

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

const x = 3;
module.exports = x;

main.js:

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

CodePudding user response:

Looking at an other project I found what I wanted:

test.js:

global.x = 3;

main.js:

require("./test");

console.log(x);
  • Related