#Using a ConfigModule which isGlobal in a module from a separate NPM package

7 messages · Page 1 of 1 (latest)

lethal granite
#

I have a handful of different servers, and would like to extract some functionality to a separate (private) NPM package. This package will need a variable (actually a handful, but that shouldn't matter) that is currently being provided by the ConfigService. The ConfigModule is set up in the AppModule as an import:

imports: [
  ...,
  ConfigModule.forRoot({
    validate: validate,
    isGlobal: true,
    envFilePath: '../.env',
  }),
],

Then in the MyModule within the same project, I can easily use it by adding it to the imports: imports: [ConfigModule] of this module, and then using the ConfigService in MyService. So far so good.

Now when I move this module into a separate project and export it, I can correctly import and use it in my main project:

imports: [
  ...,
  MyNpmModule,
],

But when I access the ConfigService from within the MyNpmService the ConfigModule is defined, but getting any variable returns undefined. When I log the entire ConfigService object in my main application, I can see all environment variables on my local machine (as well as those in the .env file), and from MyNpmService no variables are listed at all:

ConfigService {
  internalConfig: {},
  cache: {},
  '_changes$': Subject {
    closed: false,
    currentObservers: null,
    observers: [],
    isStopped: false,
    hasError: false,
    thrownError: null
  },
  _skipProcessEnv: false,
  _isCacheEnabled: false,
  envFilePaths: []
}

How, if at all, should I be using my variables from the config service/environment in the separate NPM package MyNpmModule? Thanks!

obtuse harness
#

Could you define MyNpmModule as a dynamic module with a registerAsync method, then inject pass the values from the environment in when you register the module?

barren matrix
lethal granite
#

Awesome, thank you both!

lethal granite
barren matrix
lethal granite
#

Hmm, that's a bit tricky then. My global config module (as pasted in the question) takes in a custom env file path (../.env), I guess these variables are never actually in the environment.

Regardless on if it could work, I think using a dynamic module is a better solution anyways. Reading some random variables that may or may not be defined in my module is a recipe for disaster anyways :) Thank you again!