Reputation: 2187
I have a base file that contains a class:
File-1:
class Foo {
constructor() {
this.count = 0;
}
}
export = new Foo();
Then I import this instance in two other files:
File-2:
import Foo = require("./File-1");
Foo.count = 6;
export const logFile2Count = () => console.log(Foo.count); // 6
File-3:
import Foo = require("./File-1");
export const logFile3Count = () => console.log(Foo.count); // 0
File-4:
import { logFile2Count } from "./File-2";
import { logFile3Count } from "./File-3";
logFile2Count(); // "6"
logFile3Count(); // "0" (Expected 6)
I want the state of Foo to stay persistent throughout all files that it's imported in. I.e. I want to import a reference of Foo in each file as oppose to a copy of Foo in each file. How can I do this?
Upvotes: 1
Views: 3344
Reputation: 321
well, if there isn't any form of sync. between File-2.js
and File-3.js
modules, before reading from File-1.js
(like File-2.js
depends on File-3.js
or viceversa) i think you can only set the value directly in the common dependency File-1.js
to be 100% sure that the dependant modules read the same values.
This because the code becomes a kind of race condition
Upvotes: 0
Reputation: 2187
I am not 100% sure but after some experimentation this is because of the way require
behaves in relation to the import statement (probably something to do with the way tsc/babel is transpiling the code); It runs the entire code in the file and then gives you the exported values. If you change to use an import
statement then it will work because it gives you a reference to the class when exporting as oppose to running the whole file and giving you a new instance.
This will give you the behaviour you intend:
File-1:
class Foo {
constructor() {
this.count = 0;
}
}
const foo = new Foo();
export foo;
File-2:
import { foo } from "./File-1";
/** -- snip -- **/
Upvotes: 1
Reputation: 944
Actually I tried the below in node js using require instead import. It seems to work as expected File-1.js
class Foo {
constructor() {
this.count = 0;
}
}
module.exports = new Foo();
File-2.js
let Foo = require("./File-1");
Foo.count = 6;
module.exports.logFile2Count = () => console.log(Foo.count); // 6
File-3.js
let Foo = require("./File-1")
module.exports.logFile3Count = () => console.log(Foo.count); // 0
File-4.js
let {logFile2Count} = require("./File-2");
let {logFile3Count} = require("./File-3");
logFile2Count(); // "6"
logFile3Count(); // "0" (Expected 6)
This is the output I got
node File-4.js
6
6
Upvotes: 1