是否可以从 Javascript 中的 require() 文件中 'backwards-reference' 获取某些内容?

Is it possible to 'backwards-reference' something from a require()'d file in Javascript?

第一次使用 SO 用户,如果我的问题不够简洁,请原谅我。本质上,我已经开始从事一个接近 2000 行代码的项目,现在我决定将其重构为多个文件/模块。

我的文件以前类似于这样:

const data = {
    thingOne: "hello",
    thingTwo: "goodbye"
}

switch (command) {
    case 'hello':
        console.log(data.thingOne);
    break;
    case 'goodbye':
        console.log(data.thingTwo);
    break;
}

拆分代码后,它类似于以下内容:

data.js

module.exports = {
    thingOne: "hello",
    thingTwo: "goodbye"
}

functions.js

module.exports = {
    hello: () => {console.log(data.thingOne)},
    goodbye: () => {console.log(data.thingTwo)}
}

main.js

const data = require('data.js');
const functions = require('functions.js');
// ...

这显然行不通,因为 'data' 在 functions.js 中没有任何意义,我能看到的最明显的 'fix' 就是简单地包含 data.js 在 functions.js 中,但是如果 functions.js 和 data.js 都包含在 main.js 中,那么这意味着 data.js 的内容实质上包含了两次,这对我来说似乎是不好的做法。

我的问题最终是,我如何拆分我的代码,同时仍然能够像上面的示例一样引用变量,同时避免不良做法?

...then this'd mean that the contents of data.js are essentially included twice...

不,不是。它们被 使用 两次,但内存中只有一个模块副本;它没有两个副本。如果您在多个地方需要从 data.js 导出的信息,则在每个需要的地方导入它是完全正常的。