2

first.js

var a='this is first.js'

module.exports=a;

second.js

var a=require('./first');

console.log(a);

output:this is first.js

if i change the content of 'a' in second.js will that reflect in first.js too? if not and if possible how to do it?

first.js

var a='this is first.js'

module.export=a;

second.js

var a=require('./first');

console.log(a);
Ronish
  • 35
  • 2
  • 6
  • Here is the answer: https://stackoverflow.com/questions/48168601/change-the-value-of-imported-variable-in-es6 – Almog Gabay Jul 24 '19 at 11:04
  • Possible duplicate of [Change the value of imported variable in ES6](https://stackoverflow.com/questions/48168601/change-the-value-of-imported-variable-in-es6) – Hardik Shah Jul 24 '19 at 11:06
  • No. The reverse is possible with ES6 modules, but not in CommonJS modules. There you can only share and manipulate an exports object. – Bergi Jul 24 '19 at 11:21
  • Btw it's `module.exports` not `module.export`. – Bergi Jul 24 '19 at 11:21

2 Answers2

1

You need to pass an object instead of string.

first.js

var a = {

    txt : 'this is first.js'
}

function too() {
    console.log(a.txt);
}
module.exports = { foo: a, too:too };

in the app.js , you can modify it and it will be reflected eveywhere

var a = require("./first");
a.foo.txt = 'hahaha';
console.log(a.foo.txt);
a.too();

I hope it helps.

debugmode
  • 936
  • 7
  • 13
0

No. Assigning to a in the second module only changes the local variable, nothing else.

how to do it?

Export an object, not a single value. Then you can modify its properties from everywhere.

// first.js
module.exports.a = 'this is first.js';

// second.js
var first = require('./first');
console.log(first.a);
first.a = 'this is something else';
Bergi
  • 630,263
  • 148
  • 957
  • 1,375