Shared Modules & Exports

Export a provider so other modules that import this module can inject it.

Syntaxexports: [UsersService]

Providers are private to their module by default. To share a provider with other modules, add it to the module's exports array.

Import and export

If OrdersModule needs UsersService, two things must happen:

  1. UsersModule must export UsersService.
  2. OrdersModule must import UsersModule.

Then Nest can inject UsersService into anything inside OrdersModule. A module dedicated to sharing common providers is called a shared module.

Example

Example Β· typescript
// users.module.ts
@Module({
  providers: [UsersService],
  exports: [UsersService], // make it shareable
})
export class UsersModule {}

// orders.module.ts
@Module({
  imports: [UsersModule], // now UsersService is injectable here
  providers: [OrdersService],
})
export class OrdersModule {}

When to use it

  • A developer creates a DatabaseModule that exports TypeORM repositories so any feature module can import them without re-registering TypeORM.
  • A team builds a SharedModule with utility providers (LoggerService, MapperService) and imports it in every feature module.
  • An architect exports only the public API of a module (one service) while keeping internal helpers private to that module.

More examples

Module exporting a service

Shows how a module publishes a provider by listing it in exports, making it injectable in any module that imports CacheModule.

Example Β· ts
import { Module } from '@nestjs/common';
import { CacheService } from './cache.service';

@Module({
  providers: [CacheService],
  exports: [CacheService],   // exposed to importing modules
})
export class CacheModule {}

Consuming module importing shared module

ProductsModule imports CacheModule so ProductsService can inject CacheService via the shared export.

Example Β· ts
import { Module } from '@nestjs/common';
import { CacheModule } from '../cache/cache.module';
import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';

@Module({
  imports: [CacheModule],   // CacheService now injectable here
  providers: [ProductsService],
  controllers: [ProductsController],
})
export class ProductsModule {}

Re-exporting an imported module

Re-exports HttpModule from SharedModule so consumers of SharedModule automatically gain access to HttpService.

Example Β· ts
import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';

@Module({
  imports: [HttpModule],
  exports: [HttpModule],   // any module importing SharedModule also gets HttpModule
})
export class SharedModule {}

Discussion

  • Be the first to comment on this lesson.