使用nodejs覆盖另一个文件中的变量



我有一个业务场景,相当于下面的棘手情况。因此,用一种简单的方式来解决这个问题,如下所示。

File1.ts
import * from 'something';
export const var1="value of var1";
//lets say we have a variable 'x' and this needs to be exported too. However value of x is still unknown.
export const x;
File2.ts
import * from 'something';
//set the value of 'x' in File1.ts as 5
File3.ts
import * from 'something'
//I should be able to get the value of 'x' from File1.ts. But it should be equal to the value set by File2.ts which is 5

如上所述,我应该能够从某个地方设置x的值(在本例中为File2.ts(,每次我从File1.ts使用"x"时,无论是在File3.ts还是任何其他文件中,"x"的值都应该是5(从File2.ts设置(

File1.ts
var x = 99 //some unknow value
function setValueOfX(value){
x = value
}
function getValueOfX(){
return x
}
module.exports = {
setValueOfX,
getValueOfX,
}

File2.ts
const File1 = require('./File1.ts')
File1.setValueOfX(5) /// you can set the value of x using the function

File3.ts
const File1 = require('./File1.ts')
console.log(File1.getValueOfX()) /// you can get value of x by using .getValueOfX function

最新更新