代码之家  ›  专栏  ›  技术社区  ›  sandre89

JS/ES6:设置了模块的属性后,需要重新导出模块吗?

  •  0
  • sandre89  · 技术社区  · 7 年前

    据我对模块系统的了解,每当我 import 'some_module'

    但如果这是真的,我有点不明白我在一些应用程序中看到的这种模式:

    // in a 'config_some_module.js' file
    import SomeModule from 'some_module';
    
    SomeModule.attribute = 'something';
    
    export default SomeModule;
    
    // in a different file;
    import SomeModule from './config_some_module';
    

    如果每次导入一个模块时都得到相同的实例(而不是一个新实例),那么为什么需要重新导出该模块以使用在上一个文件上完成的配置来访问它?

    还有,第二个问题:如果不需要,如何确保在第二个文件中,当已经设置了该属性时,导入将获得该模块?我假设如果两个导入都得到相同的实例,那么最终属性将出现在 SomeModule 在第二个文件中,但是也许上面提到的模式是有用的,因为您可以确定对模块的更改已经应用了?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Patrick Roberts Benjamin Gruenbaum    7 年前

    你需要的理由 export config_some_module.js 只会创建一个 副作用 . 如果你想的话 import 直接的,你需要 出口 出口 任何来自 配置一些模块.js ,你需要 进口 执行此操作会产生副作用的修改对象:

    // in 'config_some_module.js' file
    import SomeModule from 'some_module';
    
    SomeModule.attribute = 'something';
    
    // in a different file;
    import './config_some_module'; // introduce side-effect
    import SomeModule from 'some_module'; // access modified object
    

    要记住的一个“问题”是,副作用只会发生一次,不管副作用发生了多少次 已导入。

    最后,执行 在消费者中的声明并不重要,只要您的使用发生在两者之后。