Shared Module

Nest Modules can export their components. It means that we can easily share component instance between them.

The best way to share an instance between two or more modules is to create Shared Module.

For example - if we want to share ChatGateway component across entire application, we could do it in this way:

import { Module, Shared } from '@nestjs/common';

@Shared()
@Module({
    components: [ ChatGateway ],
    exports: [ ChatGateway ]
})
export class SharedModule {}

Then, we only have to import this module into another modules, which should share component instance:

@Module({
    modules: [ SharedModule ]
})
export class FeatureModule {}

That's all.

3rd-party modules

If you want to share 3rd-party module, you can use Shared as a function:

@Module({
    modules: [ Shared()(ThirdPartyModule) ]
})
export class FeatureModule {}

Scope

If you don't want to share components across entire application, but only within smaller, defined scope, you can use a namespace-scoped @Shared('namespace') module.

@Module({
    modules: [ Shared('namespace')(ThirdPartyModule) ]
})
export class FeatureModule {}

results matching ""

    No results matching ""