NPM依赖关系管理中的单例类

时间:2020-01-02 00:34:34

标签: node.js reactjs npm

我对NPM依赖性管理中的单例感到怀疑。

这是我的依赖树:

- YoutubeScraper
  - ScrapperFoundation
  - YoutubeScraperCore
    - ScrapperFoundation

ScrapperFoundation包含一个单例类“ ScrapperDataService”,这两个软件包“ YoutubeScraper”和“ YoutubeScraperCore”都在使用。

我想知道这是否是“ ScrapperDataService”的两个实例吗?

如果是,那么在这种设置中实现全局单例的最佳实践是什么?

1 个答案:

答案 0 :(得分:0)

我认为您可以像这样创建一个全局单例类,

ScrapperFoundation.js

let instance = null;

class ScrapperDataService {

    constructor() {
        if (!instance) {
            instance = this;
        }
        return this;
    }
}

export default ScrapperDataService;

用法

import ScrapperDataService from './ScrapperFoundation'

new ScrapperDataService();

希望这会有所帮助。