Did node require change?
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
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);
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